﻿/**
*@Date 2010-03-22
*@Description 本文件中包括页面端一些常用JS框架、方法的封装
*/
/**
*@description 定义全局
*/
var Chenxin={};


/**
*@description 登录页面URL，全局
*/
Chenxin.loginUrl='/loginex.aspx';
Chenxin.loadImgUrl='';
Chenxin.progressImgUrl='';

/**
*@description 将config配置项的内容，赋值给tag对象
*@tag被覆盖的目标对象
*@config 用于覆盖的目标对象 
*@return 包括两者属性的对象
*/
Chenxin.apply=function(tag,config){
	if(!tag){
		tag={};
	}
	if(tag&&config&& typeof config=='object'){
		for(var c in config){
			if(c=='scope'){
				tag[c]=config[c];			
			}else{			
				if(typeof(config[c])=='object'){
					if($.isArray(config[c])){
						tag[c]=[];
						for(var i=0;i<config[c].length;i++){
							tag[c].push(config[c][i]);
						}
					}else if(config[c]==null){
						tag[c]=null;
					}else{
						tag[c]={};
						Chenxin.apply(tag[c],config[c]);
					}
				}else{
					tag[c]=config[c];			
				}
			}
		}
	}
}

/**
*@description 将config配置项的内容，在tag对象没有该配置项的情况下，赋值给tag对象
*@tag被覆盖的目标对象
*@config 用于覆盖的目标对象 
*@return 包括两者属性的对象
*/
Chenxin.applyIf=function(tag,config){
	if(!tag){
		tag={};
	}
	if(tag&&config&& typeof config=='object'){
		for(var c in config){			
			if(tag[c]==undefined){				
				if(typeof config[c]=='object'){		
					if($.isArray(config[c])){
						tag[c]=[];
						for(var i=0;i<config[c].length;i++){
							tag[c].push(config[c][i]);
						}
					}else if(config[c]==null){
						tag[c]=null;
					}else{			
						tag[c]={};
						Chenxin.apply(tag[c],config[c]);
					}					
				}else{
					tag[c]=config[c];
				}
			}else{
				if(c!='scope'&&typeof config[c]=='object'&&typeof tag[c]=='object'){
					Chenxin.applyIf(tag[c],config[c]);		
				}				
			}
		}
	}
}

/**
*@description 类的继承方法
*@superclass 父类
*@constructor JSON扩展项内容
*@return 子类
*/
Chenxin.extend=function(superclass, extendConfig){
	var clazz=function(config){
		for(var a in config){
			this[a]=config[a];
		}
		this.initComponent.apply(this,arguments);
	}
	
	//如果无参数,直接返回类.
	if(arguments.length == 0){
		return clazz;
	}
	

	//如果无父类,此时constructor应该为一个纯对象,直接复制属性返回.
	if(!superclass){
		Chenxin.apply(clazz.prototype, extendConfig);
		return clazz;
	}

	var absObj = clazz.prototype;
	var sprPropty = superclass.prototype;

	if(sprPropty){
	  
			//用于访问父类方法
	  clazz.superclass = sprPropty;
	  
	  Chenxin.apply(absObj, sprPropty);//将父类的属性复制给子类
	  //调用属性构造函数创建属性,这个是实现关键.
	  Chenxin.apply(absObj,extendConfig);
	  //$.extend(absObj, extendConfig);//sprPropty.constructor(extendConfig));
	  

	  // 子类实例直接通过obj.superclass访问父类属性,
	  // 如果不想造成过多引用,也可把这句注释掉,因为多数时候是没必要的.
	  absObj.superclass = sprPropty;
	  //
	  //clazz.constructor = constructor;
	}

	return clazz;
}

/**
*未完待续
*/
Chenxin.ns=function (nameSpaceStr){
	/*
	var nameSpaceLevel=nameSpaceStr.split('.');	
	
	if(nameSpaceLevel.length){
		if(!eval(nameSpaceLevel[0])==false){
			eval('var '+nameSpaceLevel[0]+'={};var t='+nameSpaceLevel[0]);
		}else{
			
		}
	}*/
};


/**
*@description 定义表单内容的命名空间
*/
Chenxin.FormCommon={};

/**
*@description 动态加载到本地的数据，存放数据字典等内容
*/
Chenxin.data={};
				
/**
*@description 定义默认空函数
*/
Chenxin.emptyFn=undefined;


/**
* @static   包装ajax方法，处理掉了success=-1(sesseion过期) 或者 success=0(操作逻辑错误) 两种情况
*  成功和失败的方法变为  onSuccess 和 onError ， 其他参数相同
*  @example Chenxin.ajax({
				url: 'login.aspx',
				params:param,
				method : 'POST',
				scope:this,
				onSuccess:function(data,msg){
				},
				onError:function(){
				
				}					
			}); 
*/
Chenxin.ajax=function (option){
	Chenxin.apply(option,{
		success: function(result){
			try{	
				if(typeof(result)=='string'){				
					var s=result;
					var reg=new RegExp("\r\n","g");
					s=s.replace(reg, "");
					reg=new RegExp("\r","g");
					s=s.replace(reg, "\\r");
					reg=new RegExp("\n","g");
					s=s.replace(reg, "\\n");
					eval('result='+s);
				}					
			}catch(e){	
				//alert(option.url);
				alert('数据格式返回错误！');
				if(option.onWrong){
					option.onWrong.call(option.scope,result);					
				}
				return;
			}
			if(result.success==-1){//登录超时	
				alert(result.msg||'登录超时，请重新登录！');
				
				window.location.href=Chenxin.loginUrl;
			}else if(result.success==0){//执行失败
				alert(result.msg);
				if(option.onFail){
					option.onFail.call(option.scope,result.data,result.msg);
				}
			}else if(option.onSuccess){
				option.onSuccess.call(option.scope,result.data,result.msg);
			}
		},
		error: function(){
			if(option.onError){
				alert('服务器无法响应，请稍候再试！');
				option.onError.call(option.scope);
			}
			return false;
		}
	});
	option.url+=option.url.indexOf('?')==-1?'?':'&'+'_r='+Math.random()*10000000000;
	Chenxin.applyIf(option,{dataType:'text'});
	$.ajax(option);
}

/**
*@description 对话框
*/
Chenxin.Msg={
	currentDomId:'',
	icon:{
		cycle:'x-msg-icon-cycle',
		progress:'x-msg-icon-progress',
		info:'x-msg-icon-info',
		warring:'x-msg-icon-warring',
		wrong:'x-msg-icon-wrong',
		next:'x-msg-icon-next'
	},
	/**
	*@description 创建对话框
	*@config{
		dom:'hello',
		icon:Chenxin.Msg.icon.cycle,
		title:'请等待',
		content:'加载中……',
		btnConfig:{
			y:true,
			n:false
		}
	} 
	*/
	create:function(config){	
		
		if(!config.id){
			Chenxin.Msg.currentDomId=(Math.random()*100000+'');
			Chenxin.Msg.currentDomId=Chenxin.Msg.currentDomId.substr(0,Chenxin.Msg.currentDomId.indexOf('.'));	
			config.id=Chenxin.Msg.currentDomId;
		}else{
			if($('#chenxin-msg-maskdiv-'+config.id).length){
				// $('#chenxin-msg-maskdiv-'+config.id).show();
				// $('#chenxin-msg-masktable-'+config.id).show();
				$('#chenxin-msg-maskdiv-'+config.id).remove();
				$('#chenxin-msg-masktable-'+config.id).remove();
				//return;
			}
		}
		
		var setting='';
		var _alert='';
		var domId='';
		var isBody=(config.dom==document.body);
		
		if(!isBody){
			var postion=Chenxin.Fn.getDomPosition(config.dom);
			setting+='left:'+postion.x1+'px;';
			setting+='top:'+postion.y1+'px;';
			setting+='width:'+postion.width+'px;';
			setting+='height:'+postion.height+'px;';
			setting+='border-width:0px;';
		}else{			
			setting+='left:0px;';
			setting+='top:0px;';
			setting+='width:100%;';
			setting+='height:100%;';
		}
		if(config.opcity==undefined){
			config.opcity=10;
		}
		
		_alert='<div id="chenxin-msg-maskdiv-'+config.id+'" class="x-mask-div x-mask-opcity-'+config.opcity+'" style="'+setting+'" ></div>';	
		
		if(!isBody){
			_alert+='<table id="chenxin-msg-masktable-'+config.id+'" class="x-msg-table" style="'+setting+'"><tr><td style="text-align:center;">';	
			_alert+='<table class="'+(config.tabCls||'')+'" style="'+config.tabStyle+'">';
		}else{
			_alert+='<table id="chenxin-msg-masktable-'+config.id+'" class="'+(config.tabCls||'')+' x-msg-table" style="'+(config.tabStyle||'')+'left:45%;top:35%;">';
		}
		
		//标题
		if(config.title){
			_alert+='<tr><td style="padding:5px;'+(config.isAlert?'background-image:url(\'/images/icon/msg/titlebg.png\');background-repeat:repeat-x':'')+'"><span class="x-msg-title">'+config.title+'</span>'+(config.isAlert?'<em>X</em>':'')+'</td></tr>';
		}
		//内容
		config.content=config.content||'';
		_alert+='<tr><td class="x-msg-content '+config.icon+'">'+config.content+'</td></tr>';
		
		//按钮
		if(config.btnConfig){
			_alert+='<tr><td style="text-align:right; padding-right:10px;"></td></tr>';
		}
		_alert+='</table>';
		
		
		$(document.body).append(_alert);
		if(!isBody){
			_alert+='</td></tr></table>';			
		}
		
		
		$('#chenxin-msg-masktable-'+config.id+' em').live('click',function(){
			Chenxin.Msg.hide(config.id);
		});
	},
	destory:function(domId){
		if(!domId){
			domId=Chenxin.Msg.currentDomId;
		}		
		$('#chenxin-msg-maskdiv-'+domId).remove();
		$('#chenxin-msg-masktable-'+domId).remove();
	},
	hide:function(domId){
		if(!domId){
			domId=Chenxin.Msg.currentDomId;
		}
		$('#chenxin-msg-maskdiv-'+domId).hide();
		$('#chenxin-msg-masktable-'+domId).hide();
	}
};

/**
*@description 提示对话框
*/
Chenxin.Msg.alert={
	id:'alert',
	show:function(content,title,icon){
		Chenxin.Msg.create({
			id:Chenxin.Msg.alert.id,
			dom:document.body,
			opcity:10,
			isAlert:true,
			tabStyle:'border:solid 1px #ccc;',
			icon:icon||Chenxin.Msg.icon.info,
			title:title||'提示',
			content:content||'有一个错误'
		});		
	},
	hide:function(){
		Chenxin.Msg.hide(Chenxin.Msg.alert.id);		
	}
};


/**
*@description 加载中对话框
*/
Chenxin.Msg.Loading={
	id:'loading',
	show:function(){
		Chenxin.Msg.create({
			id:Chenxin.Msg.Loading.id,
			dom:document.body,
			opcity:0,
			icon:Chenxin.Msg.icon.cycle,
			content:'Loading...'
		});
	},
	hide:function(){
		Chenxin.Msg.hide(Chenxin.Msg.Loading.id);
	}
};

/**
*@description 保存中对话框
*/
Chenxin.Msg.Saving={
	id:'saving',
	show:function(){
		Chenxin.Msg.create({
			id:Chenxin.Msg.Saving.id,
			dom:document.body,
			opcity:10,
			icon:Chenxin.Msg.icon.progress,
			title:'Saving...'
		});
	},
	hide:function(){
		Chenxin.Msg.hide(Chenxin.Msg.Saving.id);
	}	
};

/**
*@description 等待对话框
*/
Chenxin.Msg.Waiting={
	id:'waiting',
	show:function(){
		Chenxin.Msg.create({
			id:Chenxin.Msg.Waiting.id,
			dom:document.body,
			opcity:10,
			icon:Chenxin.Msg.icon.progress,
			title:'Waiting...'
		});
	},
	hide:function(){
		Chenxin.Msg.hide(Chenxin.Msg.Waiting.id);
	}	
};

/**
*@description 定义Function功能函数命名空间
*/
Chenxin.Fn={};

/**
*@description 比较日期，如果其中一个参数为空，则返回true，否则，如果date1大于date2返回true
*@date1 第一个日期，格式：2010-1-3
*@date2 第二个日期，格式：2010-1-3
*/
Chenxin.Fn.compareDate=function(date1,date2){
	if(!date1||!date2){
		return true;
	}
	var d1=date1.split('-');
	var d2=date2.split('-');
	
	var a=new Date(d1[0],parseInt(d1[1])-1,d1[2]);
	var b=new Date(d2[0],parseInt(d2[1])-1,d2[2]);
	
	return a>b;
}


/**
*@description 扩展Object的equals方法，比较两个对象的字符串是否相等
*/
Chenxin.Fn.equals=function(obj1,obj2){
	if(obj1==obj2){
		return true;
	}
	return obj1.toString()==obj2.toString();
};

/**
*@description 格式化字符串方法
*@example Chenxin.Fn.stringFormat('hello,{0}{1}','world','1');方法将返回hello,world!;
*/
Chenxin.Fn.stringFormat=function(){
	if(!arguments.length){
		return '';
	}
	var s=arguments[0];
	
	for(var i=0;i<arguments.length-1;i++){
		s=s.replace('{'+i+'}',arguments[i+1]);
	}
	return s;
}

/**
*@description 获取指定ID容器内的表单项JSON
*@formDomId 指定容器的ID
*@comboList DIV下拉框数组
*@emptyInJson 值为空时是否也转换为Json
*@regurn JSON对象 
*/
Chenxin.Fn.getFormJson=function(formDomId,comboList,emptyInJson){
	var json={};
	var filter='';
	if(formDomId){
		filter='#'+formDomId+' ';
	}
	
	//搜索password
	$(filter+':password').each(function(){
		if(this.name){
			json[this.name]=this.value;			
		}
	});
	
	//搜索text控件
	$(filter+':text').each(function(){
		if(this.name){
			if(this.defVal!=this.value){
				json[this.name]=this.value;
			}else{
				json[this.name]='';
			}
		}			
	});
	
	//搜索选中的Checkbox项
	$(filter+':checkbox:checked').each(function(){			
		/**
		*判断此名称的表单项目是否已经存在，
		*存在则追加选中值，否则声明新的属性，并设置值
		*/
		if(this.name){
			if(json[this.name]){
				json[this.name]+=','+this.value;
			}else{
				json[this.name]=this.value;
			}
		}			
	});
	//搜索选中的radio选中值
	$(filter+':radio:checked').each(function(){
		json[this.name]=this.value;
		
	});
	
	//搜索隐藏项的值
	//$(filter+':hidden').each(function(){
	$(filter+'input[type="hidden"]').each(function(){
		if(this.name&&this.value){
			json[this.name]=this.value;
		}			
	});
	
	//搜索textarea项
	$(filter+'textarea').each(function(){
		if(this.name){
			json[this.name]=this.value;
		}			
	});
	
	//搜索selected选中项
	$(filter+'select option:selected').each(function(){
		if(this.parentNode.name){				
			if(json[this.parentNode.name]){
				json[this.parentNode.name]+=','+this.value;
			}else{
				json[this.parentNode.name]=this.value;
			}
		}
	});
	if(comboList){	
		//搜索DIV下拉框
		for(var i=0;i<comboList.length;i++){
			var tempItem=comboList[i];
			if(tempItem.getValue()!=tempItem.defVal){
				if(tempItem.inModelType=='val'){					
					if(tempItem.comboType=='wincombo'){
						for(var v in tempItem.inModelName){
							json[v]=tempItem.getValue(v);
						}
					}else{						
						json[tempItem.name]=tempItem.getValue();
					}
					
				}else if(tempItem.inModelType=='txt'){				
					if(tempItem.comboType=='wincombo'){
						for(var v in tempItem.inModelName){
							json[v]=tempItem.getText(v);
						}
					}else{						
						json[tempItem.name]=tempItem.getText();	
					}		
				}else if(tempItem.inModelType=='all'){								
					if(tempItem.comboType=='wincombo'){
						for(var v in tempItem.inModelName){
							json[v]=tempItem.getValue(v);
							json[v]=tempItem.getText(v);
						}
					}else{						
						json[tempItem.name]=tempItem.getValue();
						json[tempItem.txtModelName]=tempItem.getText();
					}		
				
				}
			}
		}
	}
	
	//此参数不传或为false是，删除值为空的字段
	if(!emptyInJson){
		for(var temp in json){
			if((json[temp]+'')==''){
				delete json[temp];
			}
		}
	}
	
	return json;
}

/**
*@description 获取指定ID容器内的表单项JSON
*@formDomId 指定容器的ID
*@comboList DIV下拉框数组
*@model 需要添加到容器表单项的Json对象
*@notAutoInit 如果Model中没有值，是否初始化,设置为true时，系统将不设置初始化值
*@regurn null 
*/
Chenxin.Fn.setFormValue=function(formDomId,comboList,model,notAutoInit){
	var filter='';
	if(formDomId){
		filter='#'+formDomId+' ';
	}
	model=model||{};
	//设置password
	$(filter+':password').each(function(){
		if(this.name){
			if(model&&model[this.name]!=undefined){			
				this.value=model[this.name];
			}else{
				if(!notAutoInit){
					this.value="";				
				}
			}		
		}
	});
	
	//设置text控件
	$(filter+':text').each(function(){
		if(this.name){
			if(model&&model[this.name]!=undefined){			
				this.value=model[this.name];
			}else{
				if(!notAutoInit){
					if(this.defVal){					
						this.value=this.defVal;
					}else{
						this.value="";	
					}			
				}
			}
		}			
	});
	
	//设置选中的Checkbox项
	$(filter+':checkbox').each(function(){			
		/**
		*判断此名称的表单项目是否已经存在，
		*存在则追加选中值，否则声明新的属性，并设置值
		*/
		if(model[this.name]!=undefined){
			if(model){
				var value=model[this.name]+','
				if(value.indexOf(this.value)!=-1){
					this.checked=true;
				}else{
					this.checked=false;
				}
			}else{
				this.checked=false;
			}
		}else{
			if(!notAutoInit){
				this.checked=false;				
			}	
		}	
	});		
	
	//设置选中的Select项
	$(filter+'select').each(function(){			
		/**
		*判断此名称的表单项目是否已经存在，
		*存在则追加选中值，否则声明新的属性，并设置值
		*/
		if(model[this.name]!=undefined){
			for(var i=0;i<this.options.length;i++){
					
				if(model){
					if(this.options[i].value.indexOf(model[this.name]+',')!=-1){
						this.options[i].selected=true;
					}else{
						this.options[i].selected=false;					
					}
				}else{
					this.options[i].selected=false;						
				}
			}
		}else{
			if(this.options.length&&!notAutoInit){
				this.options[0].selected=true;
			}
		}	
	});
	
	//设置选中的radio选中值
	var radioName='';
	$(filter+':radio').each(function(i){
		if(model&&model[this.name]!=undefined){
			if(this.value==(model[this.name]+'')){
				this.checked=true;
			}else{
				this.checked=false;
			}
		}else{
			if(this.name!=radioName){
				this.checked=true;
				radioName=this.name;
			}else{
				this.checked=false;
			}			
		}
	});
	
	//设置隐藏项的值
	//$(filter+':hidden').each(function(){
	$(filter+'input[type="hidden"]').each(function(){
		if(model&&model[this.name]!=undefined){			
			this.value=model[this.name];
		}else{
			if(!notAutoInit){
				this.value="";				
			}
		}
	});
	
	//设置textarea项
	$(filter+'textarea').each(function(){
		if(model&&model[this.name]!=undefined){			
			this.value=model[this.name];
		}else{
			if(!notAutoInit){
				this.value="";				
			}
		}		
	});
	
	if(comboList){	
		//设置DIV下拉框
		for(var i=0;i<comboList.length;i++){
			var tempItem=comboList[i];
			if(tempItem._items){//普通Combo
				if(model&&model[tempItem.name]!=undefined){
					if(tempItem.inModelType=='txt'){	
						tempItem.setValeByText(model[tempItem.name]);
					}else{			
						tempItem.setValue(model[tempItem.name]);
					}
				}else{
					if(!notAutoInit){
						tempItem.setValue(tempItem.defVal);					
					}
				}		
			}else if(tempItem.root){//树Combo
			
				if(model&&model[tempItem.name]!=undefined){
					if(tempItem.inModelType=='txt'){	
						tempItem.setValeByText(model[tempItem.name]);
					}else{			
						tempItem.setValue(model[tempItem.name]);
					}
				}else{
					if(!notAutoInit){
						//tempItem.setValue(tempItem.defVal);					
					}
				}
			}else if(tempItem.comboType=='wincombo'){
				tempItem.clear();
			}
		}
	}
}

/**
*@description 处理元素的Disable操作
*@obj 元素
*@status 状态，true/false
*/
Chenxin.Fn.handlerDisabled=function(obj,status){
	if(status){
		$(obj).attr('disabled','disabled');
	}else{
		$(obj).removeAttr('disabled');
	}
	obj.disabled=status;
}

/**
*@description 设置表单项的可用性
*@formDomId 指定容器的ID
*@comboList DIV下拉框数组 暂不支持
*@status 状态，true or false
*@regurn null 
*/
Chenxin.Fn.setFormDisableStatus=function(formDomId,comboList,status){
	var filter='';
	if(formDomId){
		filter='#'+formDomId+' ';
	}
	
	//设置password
	$(filter+':password').each(function(){
		Chenxin.Fn.handlerDisabled(this,status);
		//this.disabled=status;
	});
	
	//设置text控件
	$(filter+':text').each(function(){
		Chenxin.Fn.handlerDisabled(this,status);
		//this.disabled=status;
	});
	
	//设置选中的Checkbox项
	$(filter+':checkbox').each(function(){
		Chenxin.Fn.handlerDisabled(this,status);
		//this.disabled=status;
	});		
	
	//设置选中的Select项
	$(filter+'select').each(function(){
		Chenxin.Fn.handlerDisabled(this,status);
		//this.disabled=status;
	});
	
	//设置选中的radio选中值
	$(filter+':radio').each(function(i){
		Chenxin.Fn.handlerDisabled(this,status);
		//this.disabled=status;
	});
	
	
	//设置textarea项
	$(filter+'textarea').each(function(){
		Chenxin.Fn.handlerDisabled(this,status);
		//this.disabled=status;
	});
	
	//设置DIV下拉框
	for(var i=0;i<comboList.length;i++){
		var tempItem=comboList[i];
		tempItem.disable=true;
		if(status){
			tempItem.setDisable();
		}else{
			tempItem.setEnable();
		}
	}
};

/**
*@description 设置表单项可用
*@formDomId 指定容器的ID
*@comboList DIV下拉框数组 暂不支持
*@status 状态，true or false
*@regurn null 
*/
Chenxin.Fn.setFormEnable=function(formDomId,comboList){
	Chenxin.Fn.setFormDisableStatus(formDomId,comboList,false);
};

/**
*@description 设置表单项不可用
*@formDomId 指定容器的ID
*@comboList DIV下拉框数组 暂不支持
*@regurn null 
*/
Chenxin.Fn.setFormDisable=function(formDomId,comboList){
	Chenxin.Fn.setFormDisableStatus(formDomId,comboList,true);
};

/**
*@description 创建JQModel窗体
*
*/
Chenxin.Fn.createJQWin=function(innerHtml,id,className,jqmWidth){
	innerHtml=innerHtml||'';
	id=id||'jqmWindow';
	className=className||'';
	jqmWidth=jqmWidth||'600';
	
	return '<div class="jqmWindow '+className+'" id="'+id+'" style="display:none;width:' + jqmWidth + 'px;">'+innerHtml+'</div>'
}

/**
*@description 创建JQModel窗体标题
*
*/
Chenxin.Fn.createJQTitle=function(title){
	return '<div class="jqmTitle jqDrag"><span class="title">'+title+'</span><span class="jqmClose"></span></div>'
}

/**
*@description 通用获取Model方法
*@modelId ID
*@url 交互地址
*@callBack 执行成功回调方法
*@scope 回调方法传递的作用域
*@op op,默认为getmodel
*/
Chenxin.Fn.getModel=function(modelId,url,callBack,scope,op,param){
	var _data={op:op||'getmodel',modelid:modelId};
	if(param){
		Chenxin.apply(_data,param);
	}
	Chenxin.ajax({
		type: "get",
		dataType: "json",
		url: url,
		data: _data,
		onSuccess: function(data) {
			callBack.call(scope,data.model||data);
		},
		onFail:function(data){
			Chenxin.Msg.Waiting.hide();	

				
			if(scope){
				if(scope.hide){
					scope.hide();
				}
			}			
		},
		onError:function(){
			Chenxin.Msg.Waiting.hide();
			
				
			if(scope){
				if(scope.hide){
					scope.hide();
				}
			}
		}	
	});
}

/**
*@description 导出table为excel,
*@data 要导出的tableHTML内容
*@filename 默认的文件保存名称
*/
Chenxin.Fn.exportToExcel=function(data, filename) {
    if(data){
		filename=filename||'导出数据';
		var objBody = document.getElementsByTagName("body").item(0);
		var objExpTemp = document.getElementById('objExpTemp');

		if (!objExpTemp) {
			objExpTemp = document.createElement("iframe");
			objExpTemp.setAttribute('id', 'objExpTemp');
			objExpTemp.style.display = 'none';
			objExpTemp.src = 'about:blank';
			objBody.appendChild(objExpTemp);
		}

		var myForm = objExpTemp.contentWindow.document.forms['myForm'];
		if (!myForm) {
			objExpTemp.contentWindow.document.write('<div style="display:none"><form name="myForm"><input id="expContent" name="content" type="text" /><input id="expFileName" name="fileName" type="text" /></form></div>');
		}
		var myForm = objExpTemp.contentWindow.document.forms['myForm'];
		var txtData = objExpTemp.contentWindow.document.getElementById('expContent');
		txtData.value = data;
		var txtFileName = objExpTemp.contentWindow.document.getElementById('expFileName');
		txtFileName.value = filename;
		
		myForm.action = 'ExcelTransfer.aspx';
		myForm.method = 'POST';
		myForm.submit();
	}else{
		alert('导出失败，不能导出空数据！');
	}
}

Chenxin.Fn.exportToExcelByServer = function(url, data, filename) {
    filename = filename || '导出数据';
    var objBody = document.getElementsByTagName("body").item(0);
    var objExpTemp = document.getElementById('objExpTemp_all');

    if (!objExpTemp) {
        objExpTemp = document.createElement("iframe");
        objExpTemp.setAttribute('id', 'objExpTemp_all');
        objExpTemp.style.display = 'none';
        objExpTemp.src = 'about:blank';
        objBody.appendChild(objExpTemp);
    }

    var myForm = objExpTemp.contentWindow.document.forms['myForm_all'];
    if (!myForm) {
        objExpTemp.contentWindow.document.write('<div style="display:none"><form name="myForm_all"><input id="expContent" name="content" type="text" /><input id="expFileName" name="fileName" type="text" /></form></div>');
    }

    var myForm = objExpTemp.contentWindow.document.forms['myForm_all'];

    myForm.action = url + '?' + $.param(data); ;
    myForm.method = 'POST';
    myForm.submit();
}

/**
*@description权限检查
*@url 后台交互地址
*@code 后台传递参数code
*@callBack 执行成功的回调函数
*@scope 回调函数作用域
*/
Chenxin.Fn.checkPermit=function(url,code,callBack,scope,data){	
	var _data={op:'checkpermit',code:code};
	if(data){
		Chenxin.apply(_data,data);
	}
	Chenxin.ajax({
		type: "post",
		dataType: "json",
		url: url,
		async:false,
		data: _data,
		onSuccess: function(data,msg) {
			callBack.call(scope,data,msg);
		},
		onFail:function(data,msg){
			callBack.call(scope,data,msg);
		}
	});
},

/**
*@description 获取URL的参数
*@key 要获取的参数名
*/
Chenxin.Fn.getQueryString = function(key) {
	var str = decodeURI(window.location.search);
    var reg = new RegExp("(^|&)" + key + "=([^&]*)(&|$)", "i");
    var r = str.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    } else {
        return null;
    }
};

/**
*@description 根据[{txt:'a',val:'1'}]数组生成CheckBox组
*@items [{txt:'a',val:'1'}]数组
*@name CheckBox控件的name属性
*@width 包裹CheckBox空间的DIV的宽度
*@renderTo 控件组渲染的容器ID，如果没有，函数返回生成的控件组字符串
*/
Chenxin.Fn.createCheckBoxGroup=function(items,name,width,renderTo){
	name=name||'checkboxgroup1';
	width=width||130;
	var html='';
	for(var i=0;i<items.length;i++){
		var t=Math.random()*100000+'';
		var id='cx_'+t.split('.')[0]+'_'+t.split('.')[1];
		html+='<div style="float:left;"><input type="checkbox" name="'+name+'" value="'+items[i].val+'" id="'+id+'"/><label for="'+id+'">'+items[i].txt+'</label></div>';
	}
	if(renderTo){
		$('#'+renderTo).html(html);
		return;
	}
	return html;
}

/**
*@description 删除JSON的所有属性
*/
Chenxin.Fn.initObject=function(obj){
	for(var c in obj){
		delete c;
	}
}

/**
*@description 获得元素位置,大小尺寸信息
*/
Chenxin.Fn.getDomPosition=function(oElement){
	if(typeof(oElement)=='string'){
		oElement=document.getElementById(oElement);
	}
	var p={
		width:oElement.offsetWidth,
		height:oElement.offsetHeight		
	};
	
	if(typeof( oElement.offsetParent ) != 'undefined'){
		for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent ){
			posX += oElement.offsetLeft;
			posY += oElement.offsetTop;      
		}		
		p.x1=posX;
		p.y1=posY;
	} else{
		p.x1=oElement.x;
		p.y1=oElement.y;
	}
	p.x2=p.x1+p.width;
	p.y2=p.y2+p.height;
	return p;
}

/**
 * 全角字符转为半角字符
 * @param {String} str 包含全角字符的字符串
 * @return 格式化为半角的字符串
 */
Chenxin.Fn.fullToHalfChar = function(str) {
	if(!str){
		return '';
	}
	if(!str.length){
		return '';
	}

    var myArray = [];
    for (var i = 0; i < str.length; i++) {
        if (str.charCodeAt != null && String.fromCharCode != null) {
            var charCode = str.charCodeAt(i);
            if (charCode > 0xfee0) {
                myArray[i] = String.fromCharCode(charCode - 0xfee0);
            }
            else
                myArray[i] = String.fromCharCode(charCode);
        }
    }
    return myArray.join('');  
}

/**
*@description 定义UI界面命名空间
*/
Chenxin.UI={};

Chenxin.UI.Win=Chenxin.extend(null,{
	autoInit:true,
	id:'',
	renderTo:'',
	hasCloser:true,
	hasFoot:true,
	bodyCls:'x-win-body',
	winCls:'x-win',
	footCls:'x-win-foot',
	titleCls:'x-win-title',
	mainCls:'x-win-main',
	btnCls:'x-button',
	title:'窗体',
	height:0,
	width:600,
	content:'',
	autoScroll:true,
	afterClose:Chenxin.emptyFn,
	afterHide:Chenxin.emptyFn,
	createBtn:Chenxin.emptyFn,
	createBodyDom:function(){
		var _t=$(document.createElement('div'));
		_t.addClass(this.bodyCls||'');
		if(this.height){
			_t.height(this.height);
			if(this.autoScroll){			
				_t.css('overflow','auto');
			}else{				
				_t.css('overflow','hidden');
			}
		}
		return _t;
	},
	createEl:function(){	
		var _t=$(document.createElement('div'));
		_t.addClass(this.winCls||'');
		_t.attr('id',this.id);
		_t.css('display','none');
		_t.width(this.width||600);
		return _t;
	},
	createFootDom:function(){
		var _t=$(document.createElement('div'));
		_t.addClass(this.footCls||'');
		return _t;
	},
	createTitleDom:function(){
		var _t=$(document.createElement('div'));
		_t.addClass('jqDrag');
		_t.addClass(this.titleCls||'');
		
		_t.append('<span class="x-win-title-l"></span><em>'+this.title+'</em><span class="x-win-title-r"></span>');
		
		if(this.hasCloser){
			var _close=document.createElement('a');
			_close.className='x-win-close';
			_close.title='关闭';
			var _this=this;
			$(_close).bind('click',function(){
				_this.close.call(_this);
			});
			_t.append(_close);
			//_t.append('<a class="x-win-close"></a>');
		}
		
		return _t;
	},
	getTitle:function(){
		return this.titleDom.find('em').html();
	},
	setTitle:function(title){
		this.title=title;
		this.titleDom.find('em').html(this.title);
	},
	setWidth:function(width){
		if(!this.width){
			return;
		}
		this.width=width;
		this.el.width(width);
	},
	init:function(){
		if(!this.el){
			this.el=this.createEl();
			
			this.titleDom=this.createTitleDom();		
			this.el.append(this.titleDom);
			
			var _m=$(document.createElement('div'));
			_m.addClass(this.mainCls||'');
			
			this.el.append(_m);
			this.bodyDom=this.createBodyDom();
			_m.append(this.bodyDom);
			if(this.hasFoot){
				this.footDom=this.createFootDom();
				this.initButton(this.footDom);
				_m.append(this.footDom);
			}
			this.bodyDom.append(this.content);
			this.render();		
		}
	},
	initButton:function(renderDom){	
		if(this.createBtn&&renderDom){
			var _b=this.createBtn.call(this);
			for(var i=_b.length-1;i>-1;i--){
				var _a=$(document.createElement('a'));
				//_a.attr('href','#');
				_a.addClass('fr');
				_a.addClass(this.btnCls||'');
				_a.append('<span title="'+_b[i].text+'">'+_b[i].text+'</span>');
				
				if(_b[i].icon){
					_a.find('span').addClss(_b[i].icon);
				}
				var sc=_b[i].scope||this;
				if(_b[i].handler){
					var f=_b[i].handler;
					_a.bind('click',{fn:_b[i].handler,scope:sc},function(e){
						e.data.fn.call(e.data.scope);
					});
				}
				
				renderDom.append(_a);
			}
		}
	},
	render:function(){		
		if(!this.renderTo){
			$(document.body).append(this.el);		
		}else{
			$('#'+this.render).append(this.el);				
		}
		this.el.jqm({ trigger: false}).jqDrag('.jqDrag');
	},
	show:function(){
		this.init();
		this.el.jqmShow();
	},
	close:function(){
		this.el.jqmHide();
		if(this.afterClose){
			this.afterClose.call(this);
		}
	},
	hide:function(){
		this.el.jqmHide();
		if(this.afterHide){
			this.afterHide.call(this);
		}
	},
	resetContent:function(content){
		content=content||this.content;
		this.content=content;
		this.bodyDom.empty();
		this.bodyDom.append(content);
	},
	initComponent:function(){
		if(!this.id){
			throw new Error('id is need!');
		}
		if(this.autoInit){
			this.init();	
		}
	}
});

/**
*@description 下拉框基类
*@extend Selector
*/
Chenxin.UI.Combo = Chenxin.extend(Selector, {
    actionUrl: '',
    addPleaseSelected: true,
    showMode: 'single',
    defVal: '请选择',
    defTxt: '请选择',
    txtModelName: '', //在inModel的时候，inModelType为all时,保存显示值的属性名
    autoLoad: false,
    required: false, //是否必选
    param: {},
    paramType: 'text',
    items: [],
    /**
    *val时，用name属性保存值;
    *txt时，用name属性保存显示值;
    *all时，用name属性保存值，txtModelName属性保存显示值
    */
    inModelType: 'val',
    /**
    *兼容以前的AJAX方法调用，若为new，则调用Chenxin.ajax({});
    *返回数据格式为{success:'',msg:'',data:''}
    */
    typeModel: 'old',//此属性已废弃
    tbxWidth: 90,
	hasPage:false,			//是否有分页
	hasSearch:false,		//是否有查询
	pageSize:20,			//每页显示记录数
	currentPageIndex:0,		//当前显示的页
    afterSetValue: Chenxin.emptyFn,
    setValue: function(newValue) {
        var oldValue = this.getValue();
		
		var v=newValue;
		if(typeof(newValue)=='string'){
			v=newValue.split(',');
		}
        Chenxin.UI.Combo.superclass.setValue.call(this, v);
        if (this.afterSetValue) {
            this.afterSetValue(newValue, oldValue);
        }
    },
    getValue: function() {
        if (this._val != undefined) {
            if (this.showMode == 'multi') {
				var v=this._val+'';
				return v.replace(this.defVal,'');
            }
            return this._val;
        } else {
            return "";
        }

    },
	getValueRecord:function(value){
		var json;
		var _v=value||this._val;
		
		if(_v) {
			if (this.showMode == 'multi'&&!value) {
				_v=','+_v+',';
				json=[];				
				for(var i=0;i<this.items.length;i++){
					if(_v.indexOf(','+this.items[i].val+',')!=-1){
						json.push(this.items[i]);
					}
				}
			
			}else{
				for(var i=0;i<this.items.length;i++){
					if(_v==this.items[i].val){
						json=this.items[i];
						break;
					}
				}
			}
			return json;
		}
		
		return {};

		
	},
	reset:function(){
		if(this.autoLoad||!this.actionUrl){
			this.setValue(this.defVal);
		}else{
			this.clearItems();
		}
	},
	resetValue:function(){
		this.setValue(this.defVal);
	},
    getText: function() {		
        if (this._txt != undefined) {
            if (this.showMode == 'multi') {
				var t=this._txt+'';
				return t.replace(this.defTxt,'');
            }
            return this._txt;
        } else {
            return "";
        }
    },
    clearItems: function() {
        this.items = [];
        this.addPleaseSelected = true;
        $(this.containerId).empty();
        this.init();
    },
    setValeByText: function(txt) {
		var v='';
		if(this.showMode=='multi'){
			txt+=',';
			for (var i = 0; i < this.items.length; i++) {
				var t=this.items[i].txt+',';
				if (txt.indexOf(t)!=-1) {
					v+=this.items[i].val+',';
				}
			}
			if(v.length){
				v=v.substr(0,v.length-1);
			}
		}else{
			v=this.defVal;
			for (var i = 0; i < this.items.length; i++) {
				if (txt == this.items[i].txt) {
					v=this.items[i].val;
					break;
				}
			}		
		}
        this.setValue(v);
    },
    afterLoadItems: Chenxin.emptyFn,
    afterInit: Chenxin.emptyFn,
    setDisable: function() {
        this.disable = true;
		//已修改源代码
        var containerId = this.containerId;
        setTimeout(function() {
            $(containerId).unbind();
        }, 200);
    },
    setEnable: function() {
        this.disable = false;
		//已修改源代码
        Chenxin.UI.Combo.superclass.refresh.call(this, this.items, this.getText(), this.getValue());
    },
    onSelected: function(obj) {//级联事件
    },
    loadItems: function(isInit, initVal) {
        var _this = this;
        Chenxin.ajax({
			type: "get",
			dataType: this.paramType,
			url: this.actionUrl,
			data: this.param,
			scope: this,
			onSuccess: function(data, msg) {
				if (data.items == undefined) {
					data.items = [];
				}
				this.items = data.items;
				if (this.afterLoadItems) {
					this.afterLoadItems(isInit,initVal);
				}
				this.handlerItems();
				if (isInit) {//是否是初始化					
					this.init();
				} else {
					if (this.initValue) {
						initVal = this.initValue;
						delete this.initValue;
					}
					if (!initVal) {
						Chenxin.UI.Combo.superclass.refresh.call(this, this.items, this.defTxt, this.defVal);
					} else {
						if (this.inModelType == 'txt') {
							Chenxin.UI.Combo.superclass.refresh.call(this, this.items, initVal, this.findValByTxt(initVal));
						} else {
							Chenxin.UI.Combo.superclass.refresh.call(this, this.items, this.findTxtByVal(initVal), initVal);
						}
					}
				}

				if (this.disable) {
					this.setDisable();
				}
			}
		});
    },
    findTxtByVal: function(val) {
		this._items=this.items;
        return Chenxin.UI.Combo.superclass.findTxtByVal.call(this, val);
    },
    findValByTxt: function(txt) {
        var val = '';
		txt=','+txt+',';
        for (var i = 0; i < this.items.length; i++) {
            if (txt.indexOf(','+this.items[i].txt+',')!=-1) {
				if(this.showMode=='multi'){				
					val +=','+this.items[i].val;
				}else{					
					val=this.items[i].val;
					break;
				}
            }
        }
		if(this.showMode=='multi'){
			return val.substr(1).split(',');
		}
        return val;
    },
    reload: function(initVal) {
        if (this.initValue) {
            this.loadItems(true);
        } else {
            this.loadItems(false, initVal);
        }
    },
    handlerItems: function() {
        if (this.addPleaseSelected) {
		
            if (!this.items.length) {
                this.items.unshift({ txt: this.defTxt, val: this.defVal });
            } else {
                if (this.items[0].txt != this.defTxt&&this.showMode!='multi') {
                    this.items.unshift({ txt: this.defTxt, val: this.defVal });
                }
            }
        }
    },
    init: function() {
        this.handlerItems();
        if (!this.name) {
            this.name = this.containerId.substring(1, this.containerId.length);
        }
        Chenxin.UI.Combo.superclass.initialize.call(this, this);
        if (!this.addPleaseSelected && this.items.length) {
            this.setValue(this.items[0].val);
        }

        if (this.initValue) {//加载后的默认初始值设置，只是用一次，过时做法，此做法将触发afterSetVal事件
            if (this.inModelType == 'txt') {
                this.setValeByText(this.initValue);
            } else {
                this.setValue(this.initValue);
            }
            delete this.initValue;
        }

        if (this.afterInit) {
            this.afterInit();
        }
    },
    initValidator: function() {
		if(!$('#'+this.name+'Tip').length){
			$(this.containerId).after('<div id="' + this.name + 'Tip" style="float:left; margin-left: 5px; width: 50px; height: 26px; line-height: 26px; text-align: left; display:none" class="onError fl">请选择！</div>');		
		}
    },
    validator: function() {
        if (!this.required) {
			$('#' + this.name + 'Tip').hide();
            return true;
        }
		this.initValidator();
        if (this._val == this.defVal) {
            $('#' + this.name + 'Tip').show();
            return false;
        }
        $('#' + this.name + 'Tip').hide();
        return true;
    },
    initComponent: function() {
        if (this.autoLoad) {
            this.loadItems(true);
        } else {
            this.init();
        }
        if (this.disable) {
            this.setDisable();
        }
        if (this.required) {
            this.initValidator();
        }
    }
});

/**
*@description jqm窗体表单基类
*@extend null
*/
Chenxin.UI.FormCommon=Chenxin.extend(null,{
	id:'',
	autoCheckPermit:true,	//是否在弹出层的时候，自动检查权限
	alwaysCheckPermit:false,//是否一致调用权限检查方法，不过之前是否做过权限检查操作
	autoResetFormVal:true,	//是否在显示DIV层之前，重置表单验证状态
	comboList:[],
	actionUrl:'',
	autoHide:true,			//保存成功后是否自动隐藏弹出层，适用于type为"jqmodel"弹出层表单
	autoReset:true,			//保存成功后是否自动重置表单项，适用于type为"numal"非弹出层表单
	autoAlertSucc:true,		//保存成功后是否自动弹出保存成功的消息
	op:'add',
	renderTo:'',
	title:'添加',
	type:'jqmodel',//jqmodel为弹出式窗体，numal为普通页面的表单
	defBBtn:false,			//默认按钮，即『确定』和『取消』
	jqmHasFoot:true,		//弹出窗体是否显示底部部分
	scope:this,
	autoInit:true,
	formValConfig:{},
	winCls:'',
	disabled:false,
	additionalParam:{},
	jqmWidth:0,
	jqmHeight:0,
	permit:{},//权限
	permitParam:{},
	createComboList:Chenxin.emptyFn,
	/**
	*@description 在获取表单Json对象后，优化处理
	*@return null
	*/
	afterGetFormJson:Chenxin.emptyFn,
	/**
	*@description 将Json对象填充到表单之前处理
	*@return null
	*/
	beforeFitData:Chenxin.emptyFn,
	/**
	*@description 将Json对象填充到表单之后的处理
	*/
	afterFitData:Chenxin.emptyFn,
	/**
	*@description 显示之后，显示成功，权限检查等成功的调用方法
	*/
	afterShow:Chenxin.emptyFn,
	/**
	*@description 初始化表单验证，需重写
	*/		
	initFormValidator:Chenxin.emptyFn,
	saveSucc:Chenxin.emptyFn,
	saveFail:Chenxin.emptyFn,
	saveError:Chenxin.emptyFn,
	createForm:Chenxin.emptyFn,
	
	/**
	*@description 后台交互确认权限的方法
	*@name 作为code参数传递到后台的值
	*/
	checkPermit:function(name,param){
		if(this.permit[name+'_permit']!=undefined&&!this.alwaysCheckPermit){
			return;
		}
		Chenxin.Fn.checkPermit(this.actionUrl,name,function(data,msg){
			if(data.permit!=undefined){
				this.permit[name+'_permit']=data.permit;				
			}
		},this,param);
	},
	/**
	*@description 根据名称查找表单项，先查找input控件，再查找comboList
	*/
	findByName:function(name){
		if($('#'+this.id+' input[name="'+name+'"]').length){
			return $('#'+this.id+' input[name="'+name+'"]');
		}else{
			for(var i=0;i<this.comboList.length;i++){
				if(this.comboList[i].name==name){
					return this.comboList[i];
				}
			}
		}
		return $('#'+this.id+' input[name="'+name+'"]');
	},
	setDisable:function(){
		if(!this.disabled){
			this.disabled=true;
			if(this.jqmHasFoot){//新模式窗体
				this.jqWin.footDom.hide();
			}else{//兼容过去手动添加按钮的模式
				$('#'+this.id+' tr:last').hide();			
			}
			Chenxin.Fn.setFormDisable(this.id,this.comboList);
		}else{
			Chenxin.Fn.setFormDisable('xxx',this.comboList);			
		}		
	},
	setEnable:function(){
		if(this.disabled){		
			this.disabled=false;
			
			if(this.jqmHasFoot){//新模式窗体
				this.jqWin.footDom.show();
			}else{//兼容过去手动添加按钮的模式
				$('#'+this.id+' tr:last').show();			
			}
			Chenxin.Fn.setFormEnable(this.id,this.comboList);
		}
	},
	getParam:function(){
		var json=Chenxin.Fn.getFormJson(this.id,this.comboList);		
		if(this.afterGetFormJson){
			var scope=this.scope
			if(this.scope==window){
				scope=this;
			}
			this.afterGetFormJson.call(scope,json);			
		}
		return json;
	},
	fitData:function(model,notAutoInit){
		if(model){
			if(this.beforeFitData){
				this.beforeFitData.call(this.scope,model);
			}
			Chenxin.Fn.setFormValue(this.id,this.comboList,model,notAutoInit);
			if(this.afterFitData){
				this.afterFitData.call(this.scope,model);
			}
		}	
	},
	initJqm:function(selector){
		if(!selector){
			selector='#'+this.id;
		}
		$(selector).jqm({ trigger: false}).jqDrag('.jqDrag');
	},	
	reset:function(){
		this.fitData({});
	},
	resetFormVal:function(){
	    if (this.autoResetFormVal && this.initFormValidator) {
			try{
				jQuery.formValidator.resetTipState(this.id);
			}catch(e){
				alert('此表单没有添加表单验证！');
			}			
		}
	},	
	/**
	*@description 显示弹出层,默认执行权限检查，弹出成功，返回true,否则返回false
	*@permitCode 传递到后台的code，默认为this.op
	*@permitParam 传递到后台的检查权限的其他参数，默认为this.permitParam
	*/
	show:function(permitCode,permitParam){
		if(this.autoCheckPermit){	
			var code=permitCode||this.op;
			this.checkPermit(code,permitParam||this.permitParam);
			if(!this.permit[code+'_permit']){
				alert('您无该权限，请与管理员联系！');
				return false;
			}else{
				if(!this.jqWin){
					this.init();
				}
				//$('#'+this.id).jqmShow();
				this.jqWin.show();
				this.resetFormVal();
				if(this.afterShow){
					this.afterShow();
				}
				return true;
			}
		}else{			
			if(!this.jqWin){
				this.init();
			}
			this.jqWin.show();
			//$('#'+this.id).jqmShow();
			this.resetFormVal();
			if(this.afterShow){
				this.afterShow();
			}
			return true;
		}
	},
	hide:function(){
		//$('#'+this.id).jqmHide();
		this.jqWin.hide();
	},
	checkCombo:function(){
		var count=0;
		for(var i=0;i<this.comboList.length;i++){
			if(!this.comboList[i].validator()){
				count++;
			}
		}
		if(count){
			return false;
		}
		return true;
	},
	formValidator:function(model){
		if(this.initFormValidator){		
			if(!jQuery.formValidator.pageIsValid(this.id)||!this.checkCombo()){
				alert('请填写完必填(选)项再进行表单提交！');
				return false;
			}
		}else{
			if(!this.checkCombo()){
				alert('请填写完必填(选)项再进行表单提交！');
				return false;
			}
		}
		if(this.customerFormVal){
			return this.customerFormVal(model);
		}
		return true;
	},
	save:function(url){
		if(this.disabled){
			alert('当前不可提交数据！');
			return;
		}
		Chenxin.Msg.Saving.show();
		this.additionalParam={};
		var model=this.getParam();
		if(!this.formValidator(model)){	
			Chenxin.Msg.Saving.hide();
			return;
		}
		var _data={
			op:this.op
		};		
		var m=model.toString();
		if(m!='{}'){			
			_data.model=m;
		}
		
		Chenxin.apply(_data,this.additionalParam);
		var _this=this;
		Chenxin.ajax({
			type: "post",
			dataType: "json",
			url: url||this.actionUrl,
			data: _data,
			onSuccess: function(data,msg) {	
				Chenxin.Msg.Saving.hide();
				
				if(_this.autoAlertSucc){
					alert(msg);
				}		
				if(_this.saveSucc){		
					_this.saveSucc.call(_this.scope,data,msg);
				}
				if(_this.type=='jqmodel'){
					if(_this.autoHide){
						_this.hide.call(_this);
					}
				}else{
					if(_this.autoReset){
						_this.reset.call(_this);
						_this.resetFormVal.call(_this);		
					}
				}				
			},
			onFail:function(data,msg){
				Chenxin.Msg.Saving.hide();	
				if(_this.saveFail){
					_this.saveFail(_this.scope,data,msg);
				}					
			},
			onError:function(){
				Chenxin.Msg.Saving.hide();	
				if(_this.saveError){
					_this.saveError(_this.scope);
				}		
			}
		});
	},
	setTitle:function(title){
		this.jqWin.setTitle(title);
		//$('#'+this.id+' .jqmTitle span[class="title"]').text(title);
	},
	setWidth:function(width){
		if(!width){
			return;
		}
		this.jqWin.setWidth(width);
		$('#'+this.id).css('width',width+'px');
	},
	del:function(modelid,op,confirmMsg){	
		var _this=this;
		
        if (confirm(confirmMsg||'确定要删除该条记录吗？')){
			Chenxin.ajax({				
				type: "get",
				dataType: "json",
				url: this.actionUrl+(this.actionUrl.indexOf('?')==-1?'?':'&')+'modelid='+modelid,
				data: {op:op||'del'},
				onSuccess: function(data,msg) {
					if(_this.autoAlertSucc){
						alert(msg);
					}
					if(_this.type=='jqmodel'){
						if(_this.autoHide){
							_this.hide.call(_this);
						}
					}else{
						if(_this.autoReset){
							_this.reset.call(_this);
						}
					}
					if(_this.afterDelSucc){
						_this.afterDelSucc.call(_this.scope,data);
					}
				}
			});
		}
	},
	initEvent:Chenxin.emptyFn,
	/**
	*@description 自定义表单验证，在formValidator验证通过后和DIV下拉Combo验证通过后执行，可重写
	*/
	customerFormVal:Chenxin.emptyFn,
	createBBtn:Chenxin.emptyFn,
	init:function(){
		if(this.type=='jqmodel'){
			//this.jqWin=Chenxin.Fn.createJQWin(Chenxin.Fn.createJQTitle(this.title)+this.createForm(),this.id,this.winCls,this.jqmWidth);
			//document.getElementById(this.renderTo).innerHTML=this.jqWin;
			
			//this.initJqm();
			var _this=this;
			
			
			this.jqWin=new Chenxin.UI.Win({
				id:this.id,
				width:parseInt(_this.jqmWidth),
				title:this.title,
				hasFoot:_this.jqmHasFoot,
				height:_this.jqmHeight,
				content:this.createForm(),
				createBtn:function(){
					if(_this.defBBtn){
						return [{
							text:'确定',
							handler:_this.save,
							scope:_this
						},{
							text:'取消',
							handler:this.hide
						}]					
					}else{
						if(_this.createBBtn){
							return _this.createBBtn.call(_this);
						}
					}
					if(this.footDom){
						this.footDom.hide();
					}
					return [];
				}
			});
		}
		
		if(this.createComboList){
			this.comboList=this.createComboList();
		}		
		if(this.initFormValidator){
			this.initFormValidator();
		}
		if(this.initEvent){
			this.initEvent();
		}	
	},
	initComponent:function(){
		if(!this.id){
			throw new Error('id is need!');
			return; 
		}
		var _this=this;
		if(this.initFormValidator){		
			Chenxin.apply(this.formValConfig,{onsuccess:function(){	
				return true;
			},validatorgroup:this.id});
			jQuery.formValidator.initConfig(this.formValConfig);
		}
		if(this.autoInit){
			this.init();
		}
		this.permit={};
	}
});

/**
*@description 查询面板父类
*@extend null
*/
Chenxin.UI.SearchCommon=Chenxin.extend(null,{
	comboList:[],
	scope:this,
	autoReload:true,//是否在点击查询按钮后，重新加载列表，可以在afterGetParamJson方法中，加入必要的业务逻辑判断，控制该属性
	id:'',
	afterGetParamJson:Chenxin.emptyFn,
	createComboList:Chenxin.emptyFn,
	initEvent:Chenxin.emptyFn,
	getParamJson:function(){
		var json=Chenxin.Fn.getFormJson(this.id,this.comboList);
		if(this.afterGetParamJson){
			this.afterGetParamJson(json);
		}
		return json;
	},	
	reset:function(){
		Chenxin.Fn.setFormValue(this.id,this.comboList);
	},
	fitData:function(model){
		if(model){		
			Chenxin.Fn.setFormValue(this.id,this.comboList,model);
		}
	},
	initComponent:function(){
		if(this.createComboList){
			this.comboList=this.createComboList();
		}
		if(this.initEvent){
			this.initEvent();
		}
	}
});

/**
*@description 页面基类
*@extend null
*/
Chenxin.UI.PageCommon=Chenxin.extend(null,{	
	actionUrl:'',
	/**
	*@description 当前记录ID
	*/	
	currentId:'',
	/**
	*@description 权限集合
	*/
	permit:{},
	/**
	*@description 是否自动加载列表数据
	*/	
	autoLoadGrid:true,
		
	/**
	*@description 添加，弹出添加DIV
	*/
	add:function(op){
		this.form.op=op||'add';
		if(this.form.show()){		
			if(this.form.disabled){
				this.form.setEnable();
			}
		}
	},
	/**
	*@description Ajax交互，对选中记录进行删除
	*/
	del:function(op,confirmMsg,url,param,check){//删除操作
		check=check||this.currentId;
		
		if(!check){
			alert('请选择一条记录！');
			return;
		}
	
		var _this=this;
		param=param||{};
		Chenxin.applyIf(param,{op:op||'del',modelid:this.currentId});
        if (confirm(confirmMsg||'确定要删除该条记录吗？')){
			Chenxin.ajax({				
				type: "get",
				dataType: "json",
				url: url||this.actionUrl,
				data: param,
				onSuccess: function(data,msg) {
					alert(msg);
					if(_this.grid){
						_this.grid.reload();
					}
					if(_this.afterDelSucc){
						_this.afterDelSucc.call(_this,data,msg);
					}
				}
			});
		}			
	},
	delList:function(){
		if(this.grid&&this.grid.getSelectList){
			var idList=this.grid.getSelectList();
			this.del('','确定删除这几条记录吗？','',{modelid:idList},idList);
		}
	},
	
	/**
	*@description Ajax交互，根据modelid，获取Model实体JSON
	*@modelId modelId
	*@callBack 回调函数
	*/
	getModel:function(modelId,callBack,scope,url,op,data){
		Chenxin.Msg.Waiting.show();		
		var _this=this;
		data=data||{};
		Chenxin.apply(data,{op:op||'getmodel',modelid:modelId});
		Chenxin.ajax({
			type: "post",
			dataType: "json",
			url: url||this.actionUrl,
			data: data,
			onSuccess: function(data) {
				_this.currentModel=data.model;
				callBack.call(scope,data.model);
				if(_this.afterGetModel){
					_this.afterGetModel.call(_this,data.model);
				}
				Chenxin.Msg.Waiting.hide();
			},
			onFail:function(data){
				Chenxin.Msg.Waiting.hide();	
				
				if(scope){
					if(scope.hide){
						scope.hide();
					}
				}
					
			},
			onError:function(){
				Chenxin.Msg.Waiting.hide();
				
				if(scope){
					if(scope.hide){
						scope.hide();
					}
				}
			}
		});
	},
	
	/**
	*@description 查看，表单项不可编辑
	*/
	view:function(){		
		this.form.op='view';
		if(this.form.show()){
			this.getModel(this.currentId,this.form.fitData,this.form);
			this.form.setDisable();		
		}
	},
	
	/**
	*@description 编辑，弹出层，加载Model数据
	*/
	edit:function(){
		if(!this.currentId){
			alert('请先选择一条记录！');
		}else{
			this.form.op='edit';
			if(this.form.show()){			
				if(this.form.disabled){
					this.form.setEnable();
				}
				this.getModel(this.currentId,this.form.fitData,this.form);	
			}		
		}
	},

	/**
	*@description 导出数据
	*/
	exportData:function(){
		if(this.grid){		
			//执行权限检查
			if(this.permit.exportdata_permit==undefined){			
				Chenxin.Fn.checkPermit(this.actionUrl,'exportdata',function(data,msg){
					if(data.permit!=undefined){
						this.permit.exportdata_permit=data.permit;	
					}
				},this);
			}
			
			if(this.permit.exportdata_permit){			
				this.grid.exportData();
			}else{
				alert('您没有此权限，请联系管理员！');
			}
		}else{
			alert('数据导出失败，没有数据列表');
		}
	},
	
	/**
	*@description 创建Grid,暂用，需进一步封装
	*/
	createGrid:Chenxin.emptyFn,	
	
	/**
	*@description 创建Form，即JQWin,暂用，需进一步封装
	*/
	createForm:Chenxin.emptyFn,	
	
	/**
	*@description 创建Grid,暂用，需进一步封装
	*/
	createSearch:Chenxin.emptyFn,	
	
	/**
	*@description 初始化页面元素事件处理，需重写
	*/
	initEvent:Chenxin.emptyFn,
		
	/**
	*@description 用户自定义页面初始化方法
	*/
	customerInit:Chenxin.emptyFn,
	
	/**
	*@description 在GetModel成功后，调用的方法
	*/
	afterGetModel:Chenxin.emptyFn,
	
	/**
	*@description 查询
	*/
	reloadGrid:function(searchModel,pageIndex){
		if(pageIndex==undefined){
			pageIndex=0;
		}
		if(!searchModel){
			if(this.search){			
				searchModel=this.search.getParamJson();
				if(this.search.autoReload){//在search的AfterGetFormJson中控制该属性，判断必要的业务逻辑
					this.grid.reload(searchModel,pageIndex);
				}else{
					return;
				}
			}else{	
				this.grid.reload(searchModel,pageIndex);
			}
		}else{
			this.grid.reload(searchModel,pageIndex);
		}
		//this.grid.reload(searchModel || this.search.getParamJson());
		if(this.currentId){
			delete this.currentId;
		}
		if(this.currentModel){
			delete this.currentModel;
		}
	},
	
	/**
	*@description 类初始化方法，初始化页面元素事件处理，创建Grid，初始化表单
	*/		
	initComponent:function(){
		
		//创建查询
		if(this.createSearch){
			this.search=this.createSearch();
		}
		
		//创建表格
		if(this.createGrid){
			this.grid=this.createGrid();		
		}
		
		//创建表单
		if(this.createForm){
			this.form=this.createForm();
		}
		
		if(this.customerInit){
			this.customerInit();
		}
		
		//绑定元素页面事件
		if(this.initEvent){
			this.initEvent();		
		}	
		
	}
});

/**
*@description 数据字典下拉框封装
*/
Chenxin.UI.ParameterCombo=Chenxin.extend(Chenxin.UI.Combo,{
	actionUrl:'/service/selector.ashx',
	typeModel:'new',
	key:'',
	autoLoad:true,
	reload:function(initVal){
		this.actionUrl=this.initUrl+'?key='+this.key+'&type=datadic';
		Chenxin.UI.ParameterCombo.superclass.reload.call(this,initVal);
	},
	initComponent:function(){
		if(Chenxin.data.dictionary&&Chenxin.data.dictionary[this.key.replace('.','')]){
			this.items=Chenxin.data.dictionary[this.key.replace('.','')];
			this.autoLoad=false;
			this.actionUrl='';
		}else{
			this.initUrl=this.actionUrl;
			this.actionUrl+='?key='+this.key+'&type=datadic';
		}
		
		Chenxin.UI.ParameterCombo.superclass.initComponent.call(this);
	}
});

/**
*@description 组织结构下拉框封装
*/
Chenxin.UI.StructCombo=Chenxin.extend(Chenxin.UI.Combo,{
	actionUrl:'/service/structhandler.ashx',
	typeModel:'new',
	autoLoad:true,
	initComponent:function(){
		Chenxin.UI.StructCombo.superclass.initComponent.call(this);
	}
});

/**
*建筑年限下拉
*/
Chenxin.UI.BuildingYearCombo=Chenxin.extend(Chenxin.UI.Combo,{
	containerId:'#community_CompleteYear',
	name:'CompleteYear',
	colNum:4,
	initComponent:function(){
		this.items=comboCommon.buildingYear();
		Chenxin.UI.BuildingYearCombo.superclass.initComponent.call(this);	
	}
});

/**
*@description 分页 AJAX返回数据格式：{success:'1',msg}
*@param domId放置内容的ID，必配置
*@param actionUrl执行AJAX操作后去后台数据的地址，必配置,注意：固定参数建议最佳在actionUrl后
		例如：service/a.ashx?op='getlist'，否则在reload的时候，isReplace为true，会冲掉该参数
*@param data执行AJAX操作传递到后台的数据
*/
Chenxin.UI.Pagination=Chenxin.extend(null,{
	actionUrl:'',
	id:'',
	domId:'',//此属性已经废弃
	type: "get",
	renderTo:'',
	dataType: "text",
	data:{},
	baseParam:{},
	recordCount:0,
	pageSize:50,
	pageIndex:0,
	minHeight:0,
	width:0,
	autoLoad:true,
	expertFileName:'数据导出',
	autoShowLoading:true,//是否在后台获取列表数据时，自动弹出Loading进度
	/**
	*@description 用AJAX获得后台数据后，进行页面渲染
	*/
	render:Chenxin.emptyFn,
	/**
	*@description 是否需要AJAX获取Count
	*/
	isLoadCount:true,
	clear:function(){
		$('#'+this.renderTo).text('');
		$('#'+this.id+'_pagebar').text('');		
	},
	exportData:function(){
		Chenxin.Fn.exportToExcel(document.getElementById(this.renderTo).innerHTML,this.expertFileName);
	},
	load:function(pageIndex,isCallBack){	
		if(this.hasCount&&isCallBack){
			this.hasCount=false;
			return;
		}	
		if(this.autoShowLoading){
			Chenxin.Msg.Loading.show();		
		}
		this.pageIndex=pageIndex;
		
		//将基础参数添加进去
		Chenxin.apply(this.data,this.baseParam);
		
		Chenxin.ajax({ 
			type: this.type,
			dataType: this.dataType,
			url: this.actionUrl+(this.actionUrl.indexOf('?')!=-1?'&':'?')+'pageindex='+pageIndex+'&pagesize='+this.pageSize,
			data: this.data,
			scope:this,
			onSuccess: function(data,msg) {	
				if(data.count!=undefined){					
					this.recordCount=parseInt(data.count);
				}
				if(this.renderTo&&$('#'+this.renderTo).length){
					$('#'+this.renderTo).css('overflow','auto');
					var width=$($('#'+this.renderTo)[0].parentNode).css('width');
					if(this.width){					
						$('#'+this.renderTo).css('width',this.width+'px');
					}else{					
						$('#'+this.renderTo).css('width',width);
					}
					
					if(this.minHeight){
						$('#'+this.renderTo).css('min-height',(this.minHeight-30)+'px');
					}
						$('#'+this.renderTo).html(data.data);
					//document.getElementById(this.renderTo).innerHTML=data.data;
					if(!$('#'+this.id+'_pagebar').length){
						$('#'+this.renderTo).after('<div style="width:'+(this.width?(this.width+'px'):(width))+';" id="'+this.id+'_pagebar"></div>');
					}else{
						if(!this.recordCount){						
							$('#'+this.id+'_pagebar').text('');
						}
					}
					if(this.afterRender){
						this.afterRender(data,msg);
					}					
				}else{
					if(this.render){//如果
						this.render.call(this,data.data);
					}
				}
				
				if(this.isLoadCount&&!isCallBack){//需要ajax获取count之后，执行分页	
					this.hasCount=true;
					this.createPagination();
				}
				if(this.autoShowLoading){
					Chenxin.Msg.Loading.hide();				
				}
			},
			onWrong:function(){
				if(this.autoShowLoading){
					Chenxin.Msg.Loading.hide();				
				}							
			},
			onFail:function(){
				if(this.autoShowLoading){
					Chenxin.Msg.Loading.hide();				
				}				
			},
			onError:function(){				
				if(this.autoShowLoading){
					Chenxin.Msg.Loading.hide();				
				}
			}
		});
	},
	createPagination:function(){
		if(this.id||this.domId||this.renderTo){
			var _this=this;
			var _opt={
				items_per_page: this.pageSize,
				containerId:'#'+this.id+'_pagebar',
				current_page:this.pageIndex,
				//renderTo:'#'+this.renderTo+',',
				callback:function(pageIndex, jq){
					_this.load(pageIndex,true);
				}
			};		
			if(this.id){
				$("#"+this.id+'_pagebar').pagination(this.recordCount,_opt);
			}else{
				$('#'+this.domId).text('');
				$("#"+this.domId).pagination(this.recordCount,_opt);				
			}
		}
	},
	
	/**
	*@description 重新加载，根据新的参数
	*@param 查询参数，object 例如：{a:'1'}
	*@isCover 是否将@param覆盖当前this.data的参数，true覆盖，直接替换
	*/
	reload:function(param,isCover,currentPageIndex){
		if(param){
			if(!isCover){
				this.data=param;
			}else{
				Chenxin.apply(this.data,param);			
			}
		}
		this.init(currentPageIndex);
	},
	init:function(currentPageIndex){	
		if(this.isLoadCount){//此情况为没有count，需要执行load方法，获取得count,并获取第一页的列表数据，如果有
			//避免两次加载第一页分页数据
			this.hasCount=false;
			if(!currentPageIndex){
				this.load(0,false);			
			}else{		
				this.load(this.pageIndex,false);
			}
			
		}else{//此情况为有count，列表数据有分页的回调函数去获取
			this.createPagination();
		}
	},
	initComponent:function(){
		if(!this.id){
			this.id=this.renderTo;
		}
		if(this.autoLoad){
			this.init();
		}
	}	
});


Chenxin.UI.PageBar = Chenxin.extend(null, {
    scope: this,
    pageSize: 20,
    pageIndex: 0,
    totalRecord: 0,
    pagingCb: Chenxin.emptyFn, //分页按钮点击后的回调函数，通常执行重新加载数据
    getPageCount: function() {
        return parseInt(this.totalRecord / this.pageSize) + (this.totalRecord % this.pageSize == 0 ? 0 : 1);
    },
    createBtn: function(name, title, cls) {
        var _t = document.createElement('input');
        _t.name = name;
        _t.title = title;
        _t.className = cls;
        _t.type = 'button';

        return $(_t);
    },
    init: function() {
        var _p = document.createElement('div');
        _p.className = this.pageCls || 'x-page';
        this.el = $(_p);


        //添加分页工具条
        var t = document.createElement('table');
        $(t).appendTo(this.el);
        var tr = document.createElement('tr');
        $(tr).appendTo(t);

        //总记录数显示
        var countTd = document.createElement('td');
        countTd.style.padding = "0px 5px;";
        this.countDom = $(countTd);
        this.countDom.appendTo($(tr));

        var cls = '';

        //first
        this.firstBtn = this.createBtn('btn_first', '首页', 'x-page-first-disable');
        $(tr).append($(document.createElement('td')).append(this.firstBtn));

        //prev
        this.prevBtn = this.createBtn('btn_prev', '上一页', 'x-page-prev-disable');
        $(tr).append($(document.createElement('td')).append(this.prevBtn));

        //separator
        $(tr).append($(document.createElement('td')).addClass('x-separator'));

        //分页统计
        var pageIndexTbx = document.createElement('input');
        pageIndexTbx.type = 'text';
        pageIndexTbx.className = 'x-page-index-input';
        pageIndexTbx.value = this.pageIndex + 1;
        this.pageTbx = $(pageIndexTbx);
        var mTd = document.createElement('td');
        mTd.innerHTML = '第';
        $(mTd).append(this.pageTbx);
        $(mTd).append('页 / 共');
        this.totalSpn = $(document.createElement('span'));
        this.totalSpn.css('color', '#003399');
        this.totalSpn.text(this.totalRecord);
        $(mTd).append(this.totalSpn);
        $(mTd).append('页');
        $(tr).append(mTd);

        //separator
        $(tr).append($(document.createElement('td')).addClass('x-separator'));


        //next
        this.nextBtn = this.createBtn('btn_next', '下一页', 'x-page-next-disable');
        $(tr).append($(document.createElement('td')).append(this.nextBtn));

        //next
        this.lastBtn = this.createBtn('btn_last', '尾页', 'x-page-last-disable');
        $(tr).append($(document.createElement('td')).append(this.lastBtn));

        var _this = this;

        this.firstBtn.bind('click', function(e) {
            if (this.className == 'x-page-first-disable') {
                return;
            }
            _this.pageIndex = 0;
            _this.paging();
        });
        this.prevBtn.bind('click', function(e) {
            if (this.className == 'x-page-prev-disable') {
                return;
            }
            _this.pageIndex -= 1;
            _this.paging();
        });
        this.nextBtn.bind('click', function(e) {
            if (this.className == 'x-page-next-disable') {
                return;
            }

            _this.pageIndex += 1;
            _this.paging();
        });
        this.lastBtn.bind('click', function(e) {
            if (this.className == 'x-page-last-disable') {
                return;
            }
            _this.pageIndex = _this.getPageCount() - 1;
            _this.paging();
        });

        this.pageTbx.bind('keydown', function(e) {
            if (e.keyCode == 13 || (e.keyCode > 45 && e.keyCode < 58) || e.keyCode == 8 || (e.keyCode > 95 && e.keyCode < 106)) {
                if (e.keyCode == 13) {
                    if (!this.value) {
                        return;
                    }
                    var length = _this.getPageCount();
                    var _c = parseInt(this.value)
                    if (_c > length || _c < 1) {
                        return;
                    } else {
                        _this.pageIndex = _c - 1;
                        _this.paging();
                    }
                }
            } else {
                return false;
            }
        });
    },
    paging: function() {
        this.scope.pageIndex = this.pageIndex;
        if (this.pagingCb) {
            this.pagingCb.call(this.scope);
        }
    },
    reRender: function(total) {
        if (total != undefined) {
            this.totalRecord = total;
        }
        this.countDom.html('共<span style="color:#003399;">' + this.totalRecord + '</span>条记录 每页<span style="color:#003399;">' + this.pageSize + '</span>条 ');
        var length = this.getPageCount();
        this.totalSpn.text(length);
        this.pageTbx.val(this.pageIndex + 1);


        this.firstBtn.removeClass();
        this.prevBtn.removeClass();
        this.nextBtn.removeClass();
        this.lastBtn.removeClass();


        if (length == 1 || length == 0) {
            this.firstBtn.addClass('x-page-first-disable');
            this.prevBtn.addClass('x-page-prev-disable');
            this.nextBtn.addClass('x-page-next-disable');
            this.lastBtn.addClass('x-page-last-disable');
        } else {
            switch (this.pageIndex) {
                case 0:
                    this.firstBtn.addClass('x-page-first-disable');
                    this.prevBtn.addClass('x-page-prev-disable');
                    if (this.pageIndex == length - 1) {
                        this.nextBtn.addClass('x-page-next-disable');
                        this.lastBtn.addClass('x-page-last-disable');
                    }
                    this.nextBtn.addClass('x-page-next');
                    this.lastBtn.addClass('x-page-last');
                    break;
                case length - 1:
                    this.firstBtn.addClass('x-page-first');
                    this.prevBtn.addClass('x-page-prev');
                    this.nextBtn.addClass('x-page-next-disable');
                    this.lastBtn.addClass('x-page-last-disable');
                    break;
                default:
                    this.firstBtn.addClass('x-page-first');
                    this.prevBtn.addClass('x-page-prev');
                    this.nextBtn.addClass('x-page-next');
                    this.lastBtn.addClass('x-page-last');
                    break;
            }
        }

    },
    initComponent: function() {
        if (!this.renderTo) {
            throw new Error('renderTo is need!')
        }
        this.init();
        if (typeof (this.renderTo) == 'string') {
            $('#' + this.renderTo).append(this.el);
        } else {
            this.renderTo.append(this.el);
        }
        //this.scope.el.after(this.el);
    }
});

Chenxin.UI.BaseGrid=Chenxin.extend(null,{
	actionUrl:'',
	addRowHoverCls:true,			//添加行鼠标滑过样式
    param: {}, 						//查询参数
    baseParam: {}, 					//基础参数，不发生变化的参数，可以手动进行修改
    autoLoad: true, 				//是否自动加载数据
    gridCls: 'x-grid-main', 		//表格样式
    selectCls: 'x-grid-select', 	//行选中样式
    hoverCls: 'x-grid-hover', 		//行滑过样式
    pageCls: 'x-grid-page', 		//分页工具条样式
	rowCls:'x-grid-row',			//行样式
	footCls:'x-grid-foot',			//注脚
	titleCls:'x-grid-title',		//标题样式
	titleIcon:'x-grid-title-icon',	//标题Icon
    height:0, 						//高度
    width: 0, 						//宽度
    gridWidth: 0, 					//内嵌数据table宽度
    hasPage: true, 					//有分页
    pageIndex: 0, 					//当前页码
    pageSize: 50, 					//当前每页显示的记录条数
	count:0,
    sortField: '', 					//排序字段
    id: '', 						//ID
    renderTo: '', 					//渲染的容器   
	title:'数据列表',						//标题
	hasTitle:true,
	collapsible:false,				//是否可以收起
	exportAble:false,				//是否可以导出
	collapsedCls:'x-grid-collapse',	//收起按钮样式
	expandCls:'x-grid-expand',		//点开按钮样式
	exportCls:'x-grid-export',		//导出按钮样式
	animation:true,					//收起展开动画
    scope: this,
	expertFileName:'数据导出',	
	exportData:function(){		
		Chenxin.Fn.exportToExcel(this.mainDom.html(),this.expertFileName);
	},
	clear:function(){		
		this.mainDom.empty();
	},
	createPage: function() {
        if (this.hasPage) {
            if (!this.pageBar) {
                this.pageBar = new Chenxin.UI.PageBar({
                    scope: this,
					renderTo:this.footDom,
                    pageSize: this.pageSize,
                    pageIndex: this.pageIndex,
                    pagingCb: function() {
                        this.reload();
                    }
                });
            }
        }
    },
	load: function() {
        Chenxin.Msg.Loading.show();
        var _data = {};
        Chenxin.apply(_data, this.param);
        Chenxin.apply(_data, this.baseParam);
        _data.sort = this.sortField;
        if (this.hasPage) {
            _data.pageindex = this.pageIndex;
            _data.pagesize = this.pageSize;
        }

        var _this = this;
        Chenxin.ajax({
            type: 'get',
            dataType: 'html',
            url: this.actionUrl,
            data: _data,
            onSuccess: function(data, msg) {
				_this.count=data.count;
                if (_this.render) {
                    _this.render.call(_this, data);
                }
                if (_this.afterRender) {
                    _this.afterRender.call(_this, data, msg);
                }
                Chenxin.Msg.Loading.hide();
            },
            onWrong: function() {
                Chenxin.Msg.Loading.hide();
            },
            onFail: function() {
                Chenxin.Msg.Loading.hide();
            },
            onError: function() {
                Chenxin.Msg.Loading.hide();
            }
        });
    },
    reload: function(param,pageIndex) {
        this.param = param || this.param;
        this.clear();
		if(pageIndex!=undefined&&pageIndex>-1){
			this.pageIndex=pageIndex;
			if(this.pageBar){
				this.pageBar.pageIndex=this.pageIndex;
			}
		}
        this.load();
    },
	createTitleTool:Chenxin.emptyFn,
	afterRenderTitleTool:Chenxin.emptyFn,
	/**
	*@description 根据配置，生成按钮
	*/
	initButton:function(btnConfig,renderDom){
		if(btnConfig){
			if(typeof(renderDom)=='string'){
				renderDom=$('#'+renderDom);
			}
			for(var i=btnConfig.length-1;i>=0;i--){//var i=0;i<btnConfig.length;i++)
				var t=document.createElement('span');
				t.id=btnConfig[i].id||'';
				if(btnConfig[i].cls){
					t.className='x-grid-title-btn '+btnConfig[i].cls;
				}else{
					t.className='x-grid-title-btn'				
				}
				if(btnConfig[i].showTitle!=false){
					t.title=btnConfig[i].title||btnConfig[i].text;				
				}
				t.innerHTML=btnConfig[i].text;
				btnConfig[i].scope=btnConfig[i].scope||this;
				
				var f=btnConfig[i].handler;
				if(f){				
					$(t).bind('click',{fn:btnConfig[i].handler,scope:btnConfig[i].scope||this},function(e){
						e.data.fn.call(e.data.scope,this,e);//f.call(btnConfig.scope,this);
					});
				}
				renderDom.append(t);
			}
		}
	},
	createDom:function(cls,content){
		var _d=document.createElement('div');
		if(cls){
			_d.className=cls;		
		}
		if(content){
			_d.innerHTML=content;
		}
		return $(_d);
	},
	createTitleDom:function(){	
		return this.createDom(this.titleCls||'x-grid-title','<span class="'+this.titleIcon+'">'+this.title+'</span>');
	},
	createMainDom:function(){
		return this.createDom(this.gridCls||'x-grid-main');
	},
	createFootDom:function(){
		return this.createDom(this.footCls||'x-grid-foot');
	},
	createCollapseBtn:function(){	
		if(this.collapsible&&this.titleDom){
			this.titleDom.append('<span id="collapse_'+this.renderTo+'" class="'+this.collapsedCls+'" title="收起"></span>');
		}
	},
	createExportBtn:function(){
		if(this.exportAble&&this.titleDom){
			this.titleDom.append('<span id="export_'+this.renderTo+'" class="'+this.exportCls+'" title="导出列表">导出</span>');
		}
	},
	render:function(data){
		this.mainDom.append(data.html||data.data);
		this.mainDom.slideDown();
		this.resetRowCls(this.mainDom);
		this.resetPageBar(data);
	},
	resetPageBar:function(data){
        if (this.hasPage) {
            this.pageBar.reRender(data.count);
        }		
	},
	resetRowCls:function(dom){	
		var _obj=this;
		dom.find('tr').each(function(i){
			if(i%2==1){//奇数行，添加样式，从0开始
				$(this).addClass('x-grid-row-odd');
			}
			$(this).addClass(_obj.rowCls);
		});
	},
	setTitle:function(title){
		title=title||this.title;
		if(title!=this.title&&this.titleDom){
			this.titleDom.children().eq(0).text(title);
			this.title=title;
		}
	},
	getTitle:function(){
		return this.title;
	},
	init: function() {
		this.titleDom=this.createTitleDom();
		if(!this.hasTitle){
			this.titleDom.css('display','none');
		}
		this.el.append(this.titleDom);
		
		this.mainDom=this.createMainDom();
		this.el.append(this.mainDom);
		
		this.footDom=this.createFootDom();
		this.el.append(this.footDom);
		
		this.createPage();
		
		
		this.el.addClass('x-grid-dom');
		
		this.createCollapseBtn();
		this.createExportBtn();
		
    },
	setSize:function(){		
		if(this.width){
			this.el.css('width',this.width+'px');
		}
		if(this.height){
			this.mainDom.height(this.height);
		}
	},
	checkIsRowSelect:function(e){		
		if (e.target.tagName != 'TD') {
			return false;
		}
		return true;
	},
	initEvent: function() {
        var _obj = this;
        var _tr =$('.'+this.rowCls);
		
		if(this.addRowHoverCls){
			_tr.live('mouseover', function() {
				if ($(this).hasClass(_obj.headCls)) {
					return;
				}
				$(this).toggleClass(_obj.hoverCls);

			});
			_tr.live('mouseout', function() {
				if ($(this).hasClass(_obj.headCls)) {
					return;
				}
				$(this).toggleClass(_obj.hoverCls);
			});		
		}
		
        _tr.live('click', function(e) {
			if(!_obj.checkIsRowSelect(e)){
				return;
			}
            if ($(this).hasClass(_obj.headCls)) {
                return;
            }
            if (_obj.scope) {
                _obj.scope.currentId = this.id;
            }
            _obj.currentId = this.id;

            $('.' + _obj.selectCls).removeClass(_obj.selectCls);
            $(this).toggleClass(_obj.selectCls);
			
			//用于扩展类的事件处理
			if(_obj.rowClick){
				_obj.rowClick.call(_obj,this.id,this);			
			}
			
			//点击事件
			if(_obj.onClick){
				_obj.onClick.call(_obj.scope,this.id,this);
			}

			//选中事件
            if (_obj.afterSelect) {
                _obj.afterSelect.call(_obj.scope, this.id, this);
            }
        });
       
		
		//展开收起按钮
		$('#collapse_'+this.renderTo).live('click',function(){
			if(this.className==_obj.collapsedCls){
				this.className=_obj.expandCls;
				if(_obj.animation){				
					_obj.mainDom.slideUp();
				}else{
					_obj.mainDom.hide();
				}
				this.title='展开';
				_obj.titleDom.css('border-bottom-width','1px');
			}else{
				this.className=_obj.collapsedCls;				
				if(_obj.animation){				
					_obj.mainDom.slideDown();
				}else{
					_obj.mainDom.show();
				}
				this.title='收起';		
				_obj.titleDom.css('border-bottom-width','0px');	
			}
		});
		
		//导出按钮
		$('#export_'+this.renderTo).live('click',function(){
			_obj.exportData();
		});
		
	},
	initComponent:function(){
		if(!this.renderTo){
			throw new Error('renderTo is need!');
		}
		this.el=$('#'+this.renderTo);
		this.init();		
		this.setSize();
		this.initEvent();
		if(this.autoLoad){
			this.load();
		}
		
		if(this.createTitleTool){
			this.initButton(this.createTitleTool(),this.titleDom);
			if(this.afterRenderTitleTool){
				this.afterRenderTitleTool.call(this);
			}
		}
	}
});

/**
*@description 数据列表
*/
Chenxin.UI.Grid = Chenxin.extend(Chenxin.UI.BaseGrid, {
	columns:{},
    headCls:'x-grid-head', 		//头部样式
	bodyCls:'x-grid-body',			//身体样式
	emptyText:'没有记录',
	ml:0,
	hasRowNumber:true,
	hasCheckBox:true,
	cellHeight:23,
	colCount:0,
	/**
	*@description 创建头部工具条
	*/
	createTitleToolBar:Chenxin.emptyFn,
	afterHeadSelect:Chenxin.emptyFn,
	extensible:true,//'扩展功能，锁定列，列扩大等'
	gridType:'table',
	cellBorder:false,				//右边竖线
	sortDir:{						//排序
		field:'',				//字段名
		dir:''					//方向，asc或者desc
	},							
	exportData:function(){
		var _h='<table>';
		_h+=this.headDom.find('table').html();
		_h+=this.bodyDom.find('table').html();
		_h+='</table>';
		Chenxin.Fn.exportToExcel(_h,this.expertFileName);
	},
    createHead: function(head) {	
		this.columns=head||this.columns;
        if (this.columns && this.columns != {}) {
			this.headDom.empty();
			
			
            var _tr = document.createElement(this.rowTagName);
            var _this = this;

			//行号码
            if (this.hasRowNumber) {
                this.colCount += 1;
                $(_tr).append('<'+this.cellTagName+' class="x-grid-row-num">&nbsp;&nbsp;&nbsp;&nbsp;</'+this.cellTagName+'>');
            }
			//选择框
            if (this.hasCheckBox) {
                this.colCount += 1;				
				$(_tr).append('<'+this.cellTagName+' class="x-grid-row-chk"><input type="checkbox" name="chk_all_row" id="chk_all_'+this.renderTo+'" /></'+this.cellTagName+'>');				
            }
            
			//行头
			var _c = [];
            for (var c in this.columns) {
                var _h = this.columns[c];
                this.colCount += 1;
				
				if(_h.inField!=false){				
					_c.push(c);
				}
				var _td=this.createHeadCellDom(_h,c,true);
                $(_tr).append(_td);
            }
			
			//查询字段参数
            this.baseParam.field = _c.join(',');
			
			//渲染
			if(this.gridType=='table'){
				var tb=document.createElement('table');
				tb.style.width='100%';
				this.headDom.append($(tb).append(_tr));		
			}else if(this.gridType=='customize'){
				this.headDom.append(_tr);	
			}else if(this.gridType=='json'){
				this.headDom.append(_tr);	
			}
			this.setHeadRowWidth();
        }
    },
	/**
	*@description 生成头部内容
	*/
	createHeadCellDom:function(_h,c,autoSort,autoExtensible){
		var _td=document.createElement(this.cellTagName);
		
		if (!_h.width) {
			_h.width=160;					
		}
		if(_h.style){
			_s=_h.style.split(';');
			for(var i=0;i<_s.length;i++){
				$(_td).css(_s[i].split(':')[0],_s[i].split(':')[1]);
			}
		}
		_td.style.width = _h.width + 'px';
		if (_h.create == false) {
			_td.style.display = 'none';
		}
		_td.f = c;
		
		if(autoSort){		
			var sf=_h.sortField||'';
			sf=sf.toLowerCase();
			
			var _sf=this.sortField.split(' ')[0].toLowerCase();
			if(this.sortDir.field.toLowerCase()==sf||this.sortDir.field.toLowerCase()==c.toLowerCase()||_sf==c.toLowerCase()||_sf==sf){
				if(_sf==c.toLowerCase()||_sf==sf){
					$(_td).append('<span class="x-grid-sort-'+this.sortField.split(',')[0].split(' ')[1]+'">'+(_h.head||'')+'</span>');	
				}else{
					$(_td).append('<span class="x-grid-sort-'+this.sortDir.dir+'">'+(_h.head||'')+'</span>');
				}
			}else{
				$(_td).append('<span>'+(_h.head||'')+'</span>');				
			}
					
			$(_td).bind('click',{scope:this}, function(e) {
				if(e.target.tagName=='DD'||e.target.tagName=='SPAN'){
					e.data.scope.headSelect(this,e.data.scope.field);
				}
			});
		}else{
			$(_td).append('<span>'+(_h.head||'')+'</span>');		
		}
		
		if(autoExtensible==undefined){
			autoExtensible=true;
		}
		if(this.extensible&&!_h.items&&autoExtensible){
			var _ea=document.createElement('a');
			_ea.className='x-grid-headcell-extend';
			_ea.style.left=(_h.width-15)+'px';
			$(_ea).bind('click',{h:_h,c:c,scope:this},function(e){
				e.data.scope.showHeadExtend.call(e.data.scope,e.data.h,e.data.c,$(this));
			});
			$(_td).append(_ea);
			
				
			$(_td).bind('mouseover',{scope:this,ea:_ea}, function(e) {
				if(e.target.tagName=='DD'||e.target.tagName=='SPAN'){
					$(e.data.ea).addClass('x-grid-headcell-extend-hover');
				}else if(e.target.tagName=='A'){
					$(e.data.ea).removeClass('x-grid-headcell-extend-hover');				
				}
			});
			
			
			$(_td).bind('mouseleave',{scope:this,ea:_ea}, function(e) {
				if(e.target.tagName=='DD'||e.target.tagName=='SPAN'){
					$(e.data.ea).removeClass('x-grid-headcell-extend-hover');
				}
			});
		}
		
		return $(_td);		
	},
	lockColumn:function(isLock,el){
		if(this.columns[el.c].isLock==isLock||(this.columns[el.c].isLock==undefined&&!isLock)){
			return;
		}
		this.lockCell(isLock,el.c,this.columns);
	},
	lockCell:function(isLock,c,field,_index){
		if(!this.headExtend){
			this.createHeadList(this.columns);
		}	
		this.createLockDom();
		
		var sourceHeadDom=isLock?this.headDom:this.lockHeadDom;
		var targetHeadDom=isLock?this.lockHeadDom:this.headDom;
		_index=_index!=undefined?_index:this.getCellIndex(c,field[c].isLock);//this.getCellIndex(c,sourceHeadDom);
		
		field[c].isLock=isLock;//标记已经锁定
		
		//获取宽度
		var sourceWidth=this.getColumnsWidth(!isLock);
		var targetWidth=this.getColumnsWidth(isLock);
		
		if(isLock&&targetWidth>this.mainDom.width()){//判断锁定列宽度不能超过表格宽度
			alert('锁定列宽度不能超过表格宽度!');
			field[c].isLock=false;
			return;
		}
		
		var _this=this;
		var lockWidth=isLock?targetWidth:sourceWidth;
		
		targetHeadDom.find(this.rowTagName).width(targetWidth);		
		sourceHeadDom.find(this.rowTagName).width(sourceWidth);
		
		//设置两个Dom的宽度
		this.lockDom.width(lockWidth);
		this.unLockDom.width(this.mainDom.width()-lockWidth-1);
		
		this.lockRowCell(sourceHeadDom,targetHeadDom,sourceWidth,targetWidth,_index,isLock,c);
	},
	lockRowCell:function(sourceHeadDom,targetHeadDom,sourceWidth,targetWidth,_index,isLock,c){	
		//移动Head
		targetHeadDom.find(this.rowTagName).append(sourceHeadDom.find(this.rowTagName).children().eq(_index));
		
		var sourceBodyDom=isLock?this.bodyDom:this.lockBodyDom;
		var targetBodyDom=isLock?this.lockBodyDom:this.bodyDom;
	
		var sourceRowList=sourceBodyDom.find(this.rowTagName);
		var targetRowList=targetBodyDom.find(this.rowTagName);		
		sourceRowList.each(function(i){
			var _tr=targetRowList.eq(i);			
			_tr.append($(this).children().eq(_index));
			_tr.width(targetWidth);
			$(this).width(sourceWidth);			
		});
	},
	createLockDom:function(){
		if(!this.lockDom){
			this.lockDom=this.createDom('x-grid-lockdom');
			this.lockHeadDom=this.createHeadDom();
			this.lockHeadDom.append('<dl></dl>');
			this.lockBodyDom=this.createBodyDom();
			if(this.height){
				this.lockBodyDom.height(this.bodyDom[0].clientHeight);
				this.lockBodyDom.css('overflow','hidden');
			}
			
			this.lockDom.append(this.lockHeadDom);
			this.lockDom.append(this.lockBodyDom);
			
			this.unLockDom=this.createDom('x-grid-unlockdom');
			
			this.unLockDom.append(this.headDom);
			this.unLockDom.append(this.bodyDom);
			this.mainDom.append(this.lockDom);
			this.mainDom.append(this.unLockDom);
			this.mainDom.width(this.el.width()-2);
			
			var _width=0;
			if(this.hasRowNumber){
				this.lockHeadDom.find(this.rowTagName).append(this.headDom.find(this.cellTagName).eq(0));
				_width+=21;
			}
			if(this.hasCheckBox){
				this.lockHeadDom.find(this.rowTagName).append(this.headDom.find(this.cellTagName).eq(0));
				_width+=21;
			}
			this.lockHeadDom.find(this.rowTagName).width(_width);			
			
			var rowList=this.bodyDom.find(this.rowTagName);
			for(var i=0;i<rowList.length;i++){	
				var _row=$(document.createElement(this.rowTagName));
				_row.addClass('x-grid-lockrow');
				_row.width(_width);
				// _row.height(rowList.eq(i).height());
				_row.height(this.cellHeight);
				if(i%2==1){
					_row.addClass('x-grid-row-odd');
				}
				if(this.hasRowNumber){
					_row.append(rowList.eq(i).find(this.cellTagName).eq(0));
				}
				if(this.hasCheckBox){
					_row.append(rowList.eq(i).find(this.cellTagName).eq(0));
				}	
				this.lockBodyDom.append(_row);
			}
		}
	},
	showHeadExtend:function(_h,c,el){
		if(!this.headExtend){
			this.createHeadList(this.columns);
		}	
		this.headExtend.show();
		this.liLock[0].c=c;
		this.liUnLock[0].c=c;
		
		this.headExtend.css('left',el.offset().left+'px');			
		this.headExtend.css('top',(el.offset().top+25)+'px');
		this.headExtend.show();
	},
	createHeadList:function(field){	
		this.headExtend=$(document.createElement('ul'));
		this.headExtend.addClass('x-grid-headextend');
		this.headExtend.hide();
		
		this.liLock=$(document.createElement('li'));
		this.liLock.attr('title','锁定该列');
		this.liLock.append('<span class="x-lock-on"></span>');
		this.liLock.append('<span>锁定该列</span>');
		this.liLock.bind('click',{scope:this},function(e){
			e.data.scope.lockColumn.call(e.data.scope,true,this);
			//alert(e.data.scope.columnIndex[this.c]);
			e.data.scope.headExtend.find('li').eq(e.data.scope.columnIndex[this.c]).children().eq(2).show();
			e.data.scope.headExtend.hide();
		});
		this.headExtend.append(this.liLock);
		
		this.liUnLock=$(document.createElement('li'));
		this.liUnLock.attr('title','解锁该列');
		this.liUnLock.append('<span class="x-lock-off"></span>');
		this.liUnLock.append('<span>解锁该列</span>');
		this.liUnLock.bind('click',{scope:this},function(e){
			e.data.scope.lockColumn.call(e.data.scope,false,this);
			e.data.scope.headExtend.find('li').eq(e.data.scope.columnIndex[this.c]).children().eq(2).hide();
			e.data.scope.headExtend.hide();
		});
		this.headExtend.append(this.liUnLock);
		
		this.headExtend.append('<hr style="width:134px"/>')
	
	
		var columnCount=0;
		this.columnIndex={};
		var ii=2;
		//生成列
		for(var f in field){
			this.columnIndex[f]=ii;
			ii++;
		
			var _li=document.createElement('li');
			$(_li).append('<span class="x-chk-off'+(field[f].create!=false?' x-chk-on':'')+'"></span>');
			$(_li).append('<span>'+field[f].head||f+'</span>');
			$(_li).append('<span style="display: none;" class="x-lock-on fr"></span>');
			_li.field=f;
			_li.title=field[f].head||f;
			var _this=this;
			this.headExtend.find('li').each(function(){
				if(this.field==f){
					$(this).find('span')[fn=='hide'?'removeClass':'addClass']('x-chk-on');				
				}
			})
			if(field[f].create!=false){
				columnCount++;				
			}
			$(_li).bind('click',{scope:this},function(e){
				var h=field[this.field]
				if(h.isLock){
					alert('该列已锁定，不能隐藏！');
					return;
				}
			
				var chk=$(this).find('span').eq(0);
				if(chk.hasClass('x-chk-on')){
					if(columnCount==1){
						alert('至少保留一列显示！');
						return;
					}
					columnCount-=1;
					chk.removeClass('x-chk-on');
					e.data.scope.showColumn.call(e.data.scope,false,this.field,h,this);
				}else{
					columnCount+=1;
					chk.addClass('x-chk-on');	
					e.data.scope.showColumn.call(e.data.scope,true,this.field,h,this);				
				}
			});
			
			this.headExtend.append(_li);	
		}
		
		this.el.append(this.headExtend);
		this.headExtend.find('li').mouseover(function(){
			$(this).addClass('x-grid-headextend-hover');
		});
		this.headExtend.find('li').mouseleave(function(){
			$(this).removeClass('x-grid-headextend-hover');
		});
		
		var autoHide=null;
		
		var h=this.headExtend;
		this.headExtend.mouseleave(function(){
			autoHide=setTimeout(function(){
				h.hide();
			},400);
		});
		this.headExtend.mouseover(function(){
			if(autoHide){
				clearTimeout(autoHide);
			}
		});	
		
	},
	getCellIndex:function(c,isLock){
		isLock=isLock==undefined?false:isLock;	
		var dom=isLock?this.lockHeadDom:this.headDom;
		var index=-1;
		dom.find(this.rowTagName).children().each(function(i){
			if(this.f==c){
				index=i;
				return false;
			}
		});
		return index;
	},
	showColumn:function(isShow,c,h,el){
		if(!this.headExtend){
			this.createHeadList(this.columns);
		}	
		var _this=this;
		var fn=isShow?'show':'hide';
		h.create=isShow;
		
		if(h.isLock){//锁定列不能隐藏
			return;
		}
		
		var _index=this.getCellIndex(c,false);//锁定列不能隐藏，第二个参数为false
		//var _width=this.getColumnsWidth(false);//锁定列不能隐藏，第二个参数为false，获取的是非锁定列的宽度
		
		this.headDom.children().eq(0).children().eq(_index)[fn]();//隐藏head的cell
		//_dl.width(_width);//设置head的cell的容器宽度
		
		this.showRowColumn(_index,fn,c);
		if(this.lockDom){//判断表格是否进行过锁定，有则重新设置Dom的宽度
			var _w=this.getColumnsWidth(true);
			this.lockDom.width(_w);
			this.unLockDom.width(this.mainDom.width()-_w-1);
		}
	},
	showRowColumn:function(index,fn,c){
		var _width=this.getColumnsWidth(false);		
		var _width=_width<this.bodyDom.width()?this.bodyDom.width():_width;
		this.headDom.children().eq(0).width(_width);
		this.bodyDom.children().each(function(){
			$(this).children().eq(index)[fn]();
			$(this).width(_width);
		});
	},
    getSelectList: function() {
		return this.getSelectRecord().join(',');
    },
	getSelectLength:function(){
		if (!this.hasCheckBox) {
            return 0;
        }
		var _length=0;
        $('#' + this.renderTo + ' :checked[name="chk_row"]').each(function(i) {
            _length++;
        });
		return _length;
	},
	getSelectRecord:function(){		
        if (!this.hasCheckBox) {
            return '';
        }
        var idList = [];
        $('#' + this.renderTo + ' :checked[name="chk_row"]').each(function(i) {
            idList.push(this.value);
        });
		return idList;
	},
    clear: function() {
        this.bodyDom.empty();
		if(this.extensible&&this.lockDom){
			this.lockDom.remove();
			delete this.lockDom;
			this.mainDom.append(this.headDom);
			this.mainDom.append(this.bodyDom);
			this.unLockDom.remove();
			delete this.unLockDom;
		}
    },
	render: function(data) {
		var _obj = this;
		if (data.gridWidth){
			this.gridWidth=data.gridWidth;
		}else{
			this.gridWidth=0;
		}
		
		var _sameHead=true;
		if (data.head) {
			if(Chenxin.Fn.equals(this.columns,{})){
				_sameHead=false;
			}else{
				_sameHead=Chenxin.Fn.equals(this.oldHead,data.head);				
			}
			if(!_sameHead){
				this.oldHead={};
				Chenxin.apply(this.oldHead,data.head);					
			}
			this.createHead(_sameHead?this.columns:data.head);
        }else{
			if(this.extensible){
				this.createHead(this.columns);
			}
		}
		
		if (data.count){
			if(this.gridType=='table'){					
				this.bodyDom.append('<table cellspacing="1" style="width:100%;">'+data.html+'</table>');
			}else if(this.gridType=='customize'){				
				this.bodyDom.append(data.html);
			}
			
			var headCell=this.headDom.find(this.cellTagName);
			this.bodyDom.find(this.rowTagName).each(function(i) {
				if(_obj.hasCheckBox){
					_obj.addRowChk(this);
				}
				if(_obj.hasRowNumber){
					_obj.addRowNum(this,i);	
				}
				if((_obj.gridType=='table'&&i==0)||_obj.gridType!='table'){				
					$(this).find(_obj.cellTagName).each(function(index){
						var _hc=headCell.eq(index)[0];
						if(_hc&&_hc.f){					
							if(_obj.cellBorder){
								$(this).css('border-right-width','1px');
								$(this).width(_obj.columns[_hc.f].width);
							}else{
								$(this).width(_obj.columns[_hc.f].width+1);							
							}
							if(_obj.columns[_hc.f].style){
								var sl=_obj.columns[_hc.f].style.split(';');
								for(var ii=0;ii<sl.length;ii++){
									if(sl[ii]){
										var style=sl[ii].split(':');
										$(this).css(style[0],style[1]);
									}
								}
							}
						}
					});
				}				
            });
			if(this.extensible&&_sameHead){		
				for(var f in this.columns){
					if(this.columns[f].isLock){
						var _index=this.getCellIndex(f,false);
						if(!this.lockDom){							
							if(this.hasRowNumber){
								_index--;
							}
							if(this.hasCheckBox){
								_index--;
							}
						}
						this.lockCell(true,f,this.columns,_index);
					}
					if(this.columns[f].create==false){
						this.showColumn(false,f,this.columns[f]);
					}
				}
			}
			this.setBodyRowWidth();
			this.resetRowCls(this.bodyDom); 
			
		}else{
			if(this.gridType=='table'){					
				this.bodyDom.append('<table style="width:100%;"><tr class="x-grid-row"><td style="text-align:center;" colspan="' + this.colCount + '">'+this.emptyText+'</td></tr></table>');
			}else{	
				this.bodyDom.append('<dl style="width:100%;"><dd class="x-grid-row" style="width:100%; text-align:center;"><dd style="text-align:center;" colspan="' + this.colCount + '">'+this.emptyText+'</dd></dl>');
			}			
		}
		if(this.ml){
			this.headDom.find(this.gridType=='table'?'table':'dl').css('margin-left',-this.ml+'px');
			this.bodyDom.scrollLeft(this.ml);
		}
		
		this.resetPageBar(data);

    },
    addRowNum: function(el,index) {
		$(el).prepend(this.createRowNum(this.cellTagName,index));//'<'+this.cellTagName+' class="x-grid-row-num" style="border-right-width:1px;">' + index+ '</'+this.cellTagName+'>');
    },
	addRowChk:function(el){
		$(el).prepend(this.createRowChk(this.cellTagName,el.id));//'<'+this.cellTagName+' class="x-grid-row-chk" style="border-right-width:1px;"><input type="checkbox" id="chk_' + el.id + '" value="' + el.id + '" name="chk_row"/></'+this.cellTagName+'>');				
	},
	createRowChk:function(tagName,id){
		return '<'+tagName+' class="x-grid-row-chk" style="border-right-width:1px;"><input type="checkbox" id="chk_' + id + '" value="' + id + '" name="chk_row"/></'+tagName+'>';
	},
	createRowNum:function(tagName,index) {
		return '<'+tagName+' class="x-grid-row-num" style="border-right-width:1px;">' + (index+1)+ '</'+tagName+'>';
    },
    headSelect: function(el,field) {
        if (!this.sortDir) {
            this.sortDir = {
				field:'',
				dir:''
			};
        }
		field=field||this.columns;
        if (field[el.f].sortable) {
            $('.x-grid-sort-asc').removeClass('x-grid-sort-asc');
            $('.x-grid-sort-desc').removeClass('x-grid-sort-desc');
			
			var _s=field[el.f].sortField||el.f;
				
			if(this.sortDir.field==_s){
				if(this.sortDir.dir=='asc'){
					this.sortDir.dir='desc';
				}else{
					this.sortDir.dir='asc';
				}
			}else{
				this.sortDir.field=_s;
				this.sortDir.dir='desc';
			}
			var sf=this.sortDir.field.split(',');
			for(var i=0;i<sf.length;i++){
				sf[i]+=' '+this.sortDir.dir;
			}
			this.sortField=sf.join(',');
			//this.sortField=this.sortDir.field+' '+this.sortDir.dir;
			el.children[0].className='x-grid-sort-'+this.sortDir.dir;
			/*			
            if (this.sortDir[el.f]) {
                if (this.sortDir[el.f] == 'asc') {
                    this.sortDir[el.f] = 'desc';
                } else {
                    this.sortDir[el.f] = 'asc';
                }
            } else {
                this.sortDir[el.f] = 'asc';
            }
            this.sortDir[el.f] = this.sortDir[el.f];
            this.sortField = el.f + ' ' + this.sortDir[el.f];
            el.children[0].className = 'x-grid-sort-' + this.sortDir[el.f];
			*/
			
						
            this.sortRecord();
        }
		if(this.afterHeadSelect){
			this.afterHeadSelect(el);
		}
		
    },
    sortRecord:function(){
		this.ml=this.bodyDom.scrollLeft();
		this.reload();
	},
	createBodyDom:function(){
		return this.createDom(this.bodyCls||'x-grid-body');
	},
	createHeadDom:function(){
		return this.createDom(this.headCls||'x-grid-head');
	},
	init: function() {
		Chenxin.UI.Grid.superclass.init.call(this);	
		
		var _width=this.el.width();
		if(_width){
			this.el.css('width',_width+'px');			
		}else{
			this.el.css('width',_width+'100%');			
		}
		
		this.headDom=this.createHeadDom();
		this.mainDom.append(this.headDom);
		this.bodyDom=this.createBodyDom();
		this.mainDom.append(this.bodyDom);
		this.createHead();	

    },
	initWidth:function(){
		if(this.columns){
			var _width=this.el.width();
			var _w=0;
			var i=0;
			if(this.hasRowNumber){
				i+=1;
				//_w+=this.headDom.find(this.rowTagName).find(this.cellTagName).eq(1).width();
				_w+=20;
			}
			if(this.hasCheckBox){
				i+=1;
				//_w+=this.headDom.find(this.rowTagName).find(this.cellTagName).eq(0).width();
				_w+=20;
			}
			if(this.count){
				for(var _c in this.columns){
					if(_c.create!=false){
						_w+=this.columns[_c].width;
					}
					if(this.gridType=='table'){					
						var _tr=this.bodyDom.find('tr').eq(0);
						_tr.find('td').eq(i).width(this.columns[_c].width);
					}else if(this.gridType=='customize'){
						var _obj=this;
						this.bodyDom.find('dl').each(function(){
							//$(this).find('dd').eq(i).width(_obj.columns[_c].width+1);
							var _dd=$(this).find('dd').eq(i);
							if(_obj.cellBorder){
								_dd.css('border-right-width','1px');
								_dd.width(_obj.columns[_c].width);
							}else{
								_dd.width(_obj.columns[_c].width+1);							
							}
						});
					}
					i++;
				}			
			}
			if(_width){
				this.el.css('width',_width+'px');			
			}else{
				this.el.css('width',_width+'100%');			
			}
			
			if((_w>this.bodyDom[0].clientWidth)||(this.bodyDom[0].clientWidth-this.bodyDom[0].offsetWidth>2)){
				if(this.bodyDom[0].clientWidth){				
					if(this.gridType=='table'){			
						this.headDom.find('table').css('width',_w+'px');		
						this.bodyDom.find("table").css('width', _w+ 'px');	
					}else if(this.gridType=='customize'){
						this.headDom.find('dl').css('width',_w+20+'px');		
						this.bodyDom.find("dl").css('width', _w+20+ 'px');	
					}else if(this.gridType=='json'){
						this.headDom.find('dl').css('width',_w+20+'px');		
						this.bodyDom.find("dl").css('width', _w+20+ 'px');	
					}
				}else{
				
				}
			}else{
				if(this.gridType=='table'){			
					this.mainDom.css('border-width','1px 0px 0px 1px;');
				}else if(this.gridType=='customize'){
					//this.headDom.find('dl')[0].style.removeAttribute('width');					
				}
			}
			
			if(!this.height){
				this.bodyDom.css('border-bottom-width','0px');
			}
		}
		if (this.gridWidth) {
			this.headDom.find(this.rowTagName).css('width',this.gridWidth+'px');		
			this.bodyDom.find(this.rowTagName).css('width', this.gridWidth + 'px');
		}
	},
    getRecord:function(column){
		if(this.currentId&&column){
			return $('#'+this.currentId).find(this.cellTagName).eq(this.getCellIndex(column)).text();
		}
		return '';
	},
	getGridWidth:function(){
		if(this.gridWidth){
			return this.gridWidth;
		}
		return this.getColumnsWidth(false);
	},
	getColumnsWidth:function(isLock){		
		var _w=0;
		if(isLock||(!isLock&&!this.lockDom)){
			if(this.hasRowNumber){
				_w+=21;
			}
			if(this.hasCheckBox){
				_w+=21;
			}		
		}
		var field=this.columns;
		for(var c in field){
			if(field[c].create!=false){
				if(isLock==undefined){
					_w+=field[c].width+1;				
				}else{
					if(field[c].isLock==undefined){
						field[c].isLock=false;
					}
					if(field[c].isLock==isLock){						
						_w+=field[c].width+1;	
					}
				}
			}
		}
		if(this.gridType!='table'&&isLock==undefined){
			return _w+6;
		}
		return _w;	
	},
	setHeadRowWidth:function(){
		this.setRowWidth(this.headDom);
	},
	setBodyRowWidth:function(){		
		this.setRowWidth(this.bodyDom);
	},
	setRowWidth:function(dom){	
		this.gridWidth=this.getGridWidth();
		var _w=this.gridWidth;		
		if((_w>dom[0].clientWidth)||(dom[0].clientWidth-dom[0].offsetWidth>2)){
			if(dom[0].clientWidth){			
				var rowTagName='dl';
				if(this.gridType=='table'){
					rowTagName='table';
				}
				dom.find(rowTagName).width(_w);
			}else{
			
			}
		}else{
			if(this.gridType=='table'){			
				this.mainDom.css('border-width','1px 0px 0px 1px;');
			}
		}
	},
	rowClick:function(id,el){	
		if (this.hasCheckBox) {
			$('#' + this.renderTo + ' :checked[name="chk_row"]').attr('checked', false);
			$('#chk_' + id).attr('checked', true);
		}
	},
    initEvent: function() {
		var _obj=this;
        
		Chenxin.UI.Grid.superclass.initEvent.call(this);
		
		//点击
		$('#' + this.renderTo + ' :input[name="chk_row"]').live('click', function() {
            $('#' + this.value).toggleClass(_obj.selectCls);
			if(_obj.scope){
				_obj.scope.currentId=this.id.substr(4);
			}
			_obj.currentId=this.v;
        });
		
		//全部选中按钮事件
		$('#chk_all_'+this.renderTo).live('click',function(){
			$('#' + _obj.renderTo + ' :input[name="chk_row"]').attr('checked', this.checked);
					
			if (this.checked) {
				_obj.bodyDom.find(_obj.rowTagName).addClass(_obj.selectCls);
			} else {
				_obj.bodyDom.find(_obj.rowTagName).removeClass(_obj.selectCls);
			}
		});
		
		//移动滚动条
		this.bodyDom.scroll(function(){
			if(_obj.gridType=='table'){
				_obj.headDom.find('table').css('margin-left',-this.scrollLeft+'px');	
			}else{
				//_obj.headDom[0].scrollLeft=this.scrollLeft;
				_obj.headDom.find('dl').css('margin-left',-this.scrollLeft+'px');
				if(_obj.lockBodyDom){
					_obj.lockBodyDom[0].scrollTop=this.scrollTop;
				}
			}
		});
	},
	resetRowCls:function(dom){	
		var _obj=this;
		dom.find(this.rowTagName).each(function(i){
			if(i%2==1){//奇数行，添加样式，从0开始
				$(this).addClass('x-grid-row-odd');
			}
			$(this).addClass(_obj.rowCls);
		});
	},
    checkIsRowSelect:function(e){				
		if (e.target.tagName.toLowerCase() != this.cellTagName) {
			return false;
		}
		return true;
	},
	setSize:function(){	
		if(this.width){
			this.el.css('width',this.width+'px');
		}
		if(this.height){
			this.bodyDom.height(this.height);
		}
	},
	initComponent: function() {
		if(this.gridType=='table'){
			this.rowTagName='tr';
			this.cellTagName='td';		
		}else if(this.gridType=='customize'){
			this.rowTagName='dl';
			this.cellTagName='dd';				
		}else if(this.gridType=='json'){
			this.rowTagName='dl';
			this.cellTagName='dd';	
		}
		Chenxin.UI.Grid.superclass.initComponent.call(this);
		this.gridWidth=0;
    }
});

Chenxin.UI.ExpandGrid=Chenxin.extend(Chenxin.UI.Grid,{	
	gridType:'customize',
	rowTagName:'dl',
	cellTagName:'dd',
	rowCls:'x-expand-grid-row',
	rowExpandCls:'x-grid-row-expand',//行点击展开样式
	rowExpandAble:false,			//是否有行点击展开
	rowExpandType:'single',			//单行点击展开，其他的收起，为multi为多行展开
	rowExpandHeight:180,
	exportData:function(){
		var _h='<table>';
		this.headDom.find('dl').each(function(){
			_h+='<tr>';
			$(this).find('dd').each(function(){
				_h+='<td>'+this.innerHTML+'</td>';
			});
			_h+='</tr>';
		});
		
		this.bodyDom.find('dl').each(function(){
			_h+='<tr>';
			$(this).find('dd').each(function(){
				if(this.style.display!='none'){
					_h+='<td>'+this.innerHTML+'</td>';				
				}
			});
			_h+='</tr>';
		});
		
		_h+='</table>';
		Chenxin.Fn.exportToExcel(_h,this.expertFileName);
	},
	/**
	*@description 行点击展开
	*/
	rowExpand:Chenxin.emptyFn,	
	/**
	*@description 行点击收起
	*/
	rowCollapse:Chenxin.emptyFn,
	rowClick:function(id,el){
		Chenxin.UI.ExpandGrid.superclass.rowClick.call(this,id,el);
		if(this.rowExpandAble){
			if(this.rowExpandType=='single'){
				$('.'+this.rowExpandCls).next().css('border-top-width','0px');
				$('.'+this.rowExpandCls).each(function(){
					$(this).remove();
					if(this.id.substr(4)!=id){
						$('#'+this.id.substr(4))[0].exp=undefined;					
					}
				});
			}
			if(!el.exp){
				$(el).next().css('border-top-width','1px');
				$(el).after('<dl class="'+this.rowExpandCls+'" id="exp_'+id+'"><dd class="row-expand-td" ></dd></dl>');
				el.exp=$('#exp_'+id).find('dd');
				el.exp.height(this.rowExpandHeight);
				if(this.rowExpand){
					this.rowExpand.call(this.scope,el.exp,el,this);
				}				
			}else{
				delete el.exp;
				if(this.rowCollapse){
					this.rowCollapse.call(this.scope,el.exp,el,this);
				}
			}
		}
	},
	
	initComponent:function(){
		Chenxin.UI.ExpandGrid.superclass.initComponent.call(this);
	}
});

Chenxin.UI.JsonGrid=Chenxin.extend(Chenxin.UI.Grid,{
	gridType:'json',
	rowCls:'x-expand-grid-row',
	rowExpandCls:'x-grid-row-expand',//行点击展开样式
	maxLevel:1,
	field:{},
	sortStyle:'remote',				//排序方式，local为本地对store的排序，remote为远程服务器刷新数据排序
	extensible:true,
	afterRender:Chenxin.emptyFn,
	cellHeight:23,
	rowRenderer:Chenxin.emptyFn,
	autoOddCls:true,				//是否给奇数行添加样式
	/**
	*@description 根据记录的ID获取记录
	*@recordId 要获取记录的ID
	*/
	getRecord:function(recordId){
		// if(!this.store.map&&this.modelId){
			// this.store.map={};
			// for(var i=0;i<this.store.rows.length;i++){
				// this.store.map[this.store.rows[i][this.modelId]]={};
				// this.store.map[this.store.rows[i][this.modelId]].index=i;
			// }
		// }
		return this.store.rows[this.store.map[recordId].index];
	},
	/**
	*@description 根据记录的ID获取记录的字段
	*@recordId 要获取记录的ID
	*@field 要获取的字段
	*/
	getField:function(recordId,field){
		return this.getRecord(recordId)[field];
	},
	/**
	*@description 获取当前选中记录，没有选中则返回null
	*/
	getCurrentRecord:function(){
		if(this.currentId){
			return this.getRecord(this.currentId);
		}
		return null;
	},
	/**
	*@description 获取当前选中记录的字段，没有则返回null
	*@field 要获取的字段
	*/
	getCurrentField:function(field){
		if(this.currentId){
			return this.getCurrentRecord(this.currentId)[field];
		}
		return null;
	},
	getColumnsWidth:function(isLock){		
		var _w=0;
		if(isLock||(!isLock&&!this.lockDom)){
			if(this.hasRowNumber){
				_w+=21;
			}
			if(this.hasCheckBox){
				_w+=21;
			}		
		}
		var field=this.field;
		for(var c in field){
			if(field[c].create!=false){
				if(isLock==undefined){
					_w+=field[c].width+1;				
				}else{
					if(field[c].isLock==undefined){
						field[c].isLock=false;
					}
					if(field[c].isLock==isLock){						
						_w+=field[c].width+1;	
					}
				}
			}
		}
		if(this.gridType!='table'&&isLock==undefined){
			return _w+6;
		}
		return _w;	
	},
	getCellIndex:function(c,isLock){
		isLock=isLock==undefined?false:isLock;	
		var dom=isLock?this.lockHeadDom:this.headDom;
		var index=-1;
		var _this=this;
		dom.find(this.rowTagName).children().each(function(i){
			if(this.f==c){
				index=i;
				return false;
			}else{
				$(this).find(_this.cellTagName).each(function(ii){
					if(this.f==c){
						index=i;
						return false;
					}
				});
				if(index!=-1){
					return false;
				}
			}
		});
		return index;
	},
	lockColumn:function(isLock,el){
		if(this.field[el.c].isLock==isLock||(this.field[el.c].isLock==undefined&&!isLock)){
			return;
		}
		this.lockCell(isLock,el.c,this.field);
	},
	lockRowCell:function(sourceHeadDom,targetHeadDom,sourceWidth,targetWidth,_index,isLock,c){		
		var sourceBodyDom=isLock?this.bodyDom:this.lockBodyDom;
		var targetBodyDom=isLock?this.lockBodyDom:this.bodyDom;
		
		var sourceRowList=sourceBodyDom.find(this.rowTagName);
		var targetRowList=targetBodyDom.find(this.rowTagName);	

		var bc=this.setFieldAttr(c,'isLock',isLock,function(c,f){			
			this.headExtend.find('li').eq(this.columnIndex[f]).children().eq(2)[isLock?'show':'hide']();
		});
		
		//移动Head
		targetHeadDom.find(this.rowTagName).append(sourceHeadDom.find(this.rowTagName).children().eq(_index));
		
		sourceWidth=this.getColumnsWidth(!isLock);
		targetWidth=this.getColumnsWidth(isLock);
		
		
		var _this=this;
		var lockWidth=isLock?targetWidth:sourceWidth;
		
		targetHeadDom.find(this.rowTagName).width(targetWidth);		
		sourceHeadDom.find(this.rowTagName).width(sourceWidth);
		
		//设置两个Dom的宽度
		this.lockDom.width(lockWidth);
		this.unLockDom.width(this.mainDom.width()-lockWidth-1);
		
		
		
		sourceRowList.each(function(i){
			var _tr=targetRowList.eq(i);	
			for(var ii=0;ii<bc.length;ii++){
				_tr.append($(this).children().eq(bc[0]));			
			}
			_tr.width(targetWidth);
			$(this).width(sourceWidth);			
		});
	},
	showHeadExtend:function(_h,c,el){
		if(!this.headExtend){
			this.createHeadList(this.field);
		}	
		this.liLock[0].c=c;
		this.liUnLock[0].c=c;
		
		this.headExtend.css('left',el.offset().left+'px');			
		this.headExtend.css('top',(el.offset().top+25)+'px');
		this.headExtend.show();
	},
	showRowColumn:function(index,fn,c){
		var bc=this.setFieldAttr(c,'create',fn=='show'?true:false,function(c,f){
			this.headExtend.find('li').eq(this.columnIndex[f]).children().eq(0)[fn=='hide'?'removeClass':'addClass']('x-chk-on');
		});
		var _width=this.getColumnsWidth(false);		
		_width=_width<this.bodyDom.width()?this.bodyDom.width():_width;
		
		this.headDom.children().eq(0).width(_width);
		this.bodyDom.children().each(function(){
			for(var i=0;i<bc.length;i++){
				$(this).children().eq(bc[i])[fn]();				
			}
			$(this).width(_width);
		});
	},
	setFieldAttr:function(c,attr,value,callback){	
		var bc=[];
		var i=0;
		var dom=attr=='create'?this.headDom:(value==true?this.headDom:this.lockHeadDom);
		var _this=this;
		dom.find(this.rowTagName).children().each(function(){
			if(this.f==undefined||this.f!=''){//普通的单元格或者数字，Checkbox框，直接加1
				if(!_this.field[c].p&&this.f==c){//要查找的也是普通的单元格，找到后，直接跳出循环
					bc.push(i);
				}
				i++;
			}else if(this.f==''){//组合框
				$(this).children().each(function(){//获取子元素
					if(_this.field[this.f]){//在this.field中存在的才是底层的普通单元格，加1
						if(_this.field[c].p&&_this.field[c].p==_this.field[this.f].p){							
							_this.field[this.f][attr]=value;
							bc.push(i);
							if(callback){
								callback.call(_this,c,this.f);
							}
						}
						i++;
					}
				});
				if(bc.length){//已经找到了，跳出循环
					return false;
				}
			}
		});
		return bc;
	},
	sortRecord:function(){	
		if(!this.sortDir.field){
			return;
		}
		
		this.ml=this.bodyDom.scrollLeft();
		if(this.sortStyle=='local'){
			var _this=this;
			this.store.rows.sort(function(x,y){
				if(typeof(x[_this.sortDir.field])=='number'){									
					if(_this.sortDir.dir=='asc'){
						return parseInt(x[_this.sortDir.field])-parseInt(y[_this.sortDir.field]);					
					}
					return parseInt(y[_this.sortDir.field])-parseInt(x[_this.sortDir.field]);	
				}else{				
					if(_this.sortDir.dir=='asc'){
						return x[_this.sortDir.field].localeCompare(y[_this.sortDir.field]);				
					}
					return y[_this.sortDir.field].localeCompare(x[_this.sortDir.field]);
				}		
			});
			this.store.isSort=true;
			this.render(this.store);
		}else{
			Chenxin.UI.JsonGrid.superclass.sortRecord.call(this);
		}
	},
	exportData:function(){
		var _h='<table>';
		
		_h+='<tr style="height:22px;">';
		for(var f in this.field){
			if(this.field[f].create!=false){
				_h+='<td style="width:'+this.field[f].width+'px; border:solid 1p #ccc;">'+this.field[f].head+'</td>';			
			}
		}
		_h+='</tr>';
		
		for(var i=0;i<this.store.rows.length;i++){
			_h+='<tr style="height:22px;">';
			for(var f in this.field){
				if(this.field[f].create!=false){
					_h+='<td style="width:'+this.field[f].width+'px; border:solid 1p #ccc;">'+this.store.rows[i][f]+'</td>';
				}
			}
			_h+='</tr>';
		}
		
		_h+='</table>';
		Chenxin.Fn.exportToExcel(_h,this.expertFileName);
	},
	createHead:function(head){
		this.columns=head||this.columns;
		
        if (this.columns && this.columns != {}) {
			this.headDom.empty();
			
            var _tr = document.createElement('dl');
			var _height=25;
            var _this = this;

			//行号码
            if (this.hasRowNumber) {
                this.colCount += 1;
                $(_tr).append('<dd class="x-grid-row-num">&nbsp;&nbsp;&nbsp;&nbsp;</dd>');
            }
			//选择框
            if (this.hasCheckBox) {
                this.colCount += 1;				
				$(_tr).append('<dd class="x-grid-row-chk"><input type="checkbox" name="chk_all_row" id="chk_all_'+this.renderTo+'" /></dd>');				
            }
            
			this.field={};
            for (var c in this.columns) {				
				$(_tr).append(this.createHeadCell(this.columns[c],c));
            }
			$(_tr).find('dd').each(function(i){
				if(this.parentNode.tagName=='DL'){
					this.style.height=_this.maxLevel*_this.cellHeight+(_this.maxLevel-1)+'px';
					this.style.lineHeight=_this.maxLevel*_this.cellHeight+(_this.maxLevel-1)+'px';
				}
			});
			
			this.headDom.append(_tr);	
			this.setHeadRowWidth();
        }
	},
	createHeadCell:function(_h,c,dom,level,p){
		if(!_h.items){
			this.field[c]=_h;
			if(p){
				this.field[c].p=p;
			}
			if(level){
				_h.level=level+1;
			}			
			if(this.maxLevel<_h.level){
				this.maxLevel=_h.level;
			}
			
			return this.createHeadCellDom(_h,c,true);
		}else{
			if(level){
				_h.level=level+1;
			}else{
				_h.level=1;
			}
			dom=dom||$(document.createElement(this.cellTagName));
			dom[0].f='';
			var x=this.createHeadCellDom(_h,c,false);
			dom.append(x);
			
			var _tempc=null;
			var i=-1;
			for(var _hi in _h.items){
				var _cell=this.createHeadCell(_h.items[_hi],_hi,dom,_h.level,p||c);
				_cell.css('border-top-width','1px');
				dom.append(_cell);
				if(_h.items[_hi].create!=false){
					_tempc=_cell;
					i++;				
				}
			}
			if(_tempc){
				_tempc.css('border-right-width','0px');
			}
			
			
			dom.width((_h.width+i)||(160+i));
			x.width((_h.width+i)||(160+i));
			return dom;
		}
	},
	createStoreMap:function(){	
		if(this.store&&!this.store.map&&this.modelId){
			this.store.map={};
			for(var i=0;i<this.store.rows.length;i++){
				this.store.map[this.store.rows[i][this.modelId]]={};
				this.store.map[this.store.rows[i][this.modelId]].index=i;
			}
		}
	},
	deleteRecord:function(modelId){
		if(modelId&&this.store.map&&this.store.map[modelId]){
			this.store.rows.splice(this.store.map[modelId].index,1);
			delete this.store.map;
			this.createStoreMap();
			this.store.count-=1;
		}
	},
	reRender:function(){
		this.bodyDom.empty();
		this.render(this.store);
	},
	render:function(data){		
		var _obj = this;
		this.gridWidth=0;
		var _sameHead=true;
		if (data.head) {
			if(Chenxin.Fn.equals(this.columns,{})){
				this.oldHead={};
				Chenxin.apply(this.oldHead,data.head);
				_sameHead=false;
			}else{
				_sameHead=Chenxin.Fn.equals(this.oldHead,data.head);
			}
			//this.createHead(_sameHead?this.columns:data.head);
			this.createHead(data.head);
        }else{
			if(this.extensible){
				this.createHead(this.columns);
			}
		}
		
		this.bodyDom.empty();
		this.store=data;
		this.createStoreMap();
		if(!this.store.isSort&&this.sortDir.field&&this.sortStyle=='local'){
			this.sortRecord();
			return;
		}
		if (data.rows.length){
			if(data.rows){		
				this.bodyDom.empty();
				for(var i=0;i<data.rows.length;i++){
					this.bodyDom.append(this.createRow(data.rows[i],i));
				}
			}else{
				Chenxin.UI.JsonGrid.superclass.render.call(this,data);
			}
		}else{
			this.bodyDom.append('<dl class="x-expand-grid-row"><dd style="width: '+this.el.width()+'px; text-align: center; border-right-width: 1px;">'+this.emptyText+'</dd></dl>');		
		}
		
		if(this.afterRender){
			this.afterRender.call(this,data);
		}
				
				
		this.setBodyRowWidth();
		if(this.ml){
			this.headDom.find('dl').css('margin-left',-this.ml+'px');
			this.bodyDom.scrollLeft(this.ml);
		}
		if(this.extensible&&_sameHead){		
			var p='';
			for(var f in this.field){
				if(this.field[f].isLock){
					this.field[f].isLock=false;
					if(!this.field[f].p){
						this.lockCell(true,f,this.field);
					}else{
						if(p!=this.field[f].p){
							p=this.field[f].p;
							this.lockCell(true,f,this.field);							
						}
					}
					this.field[f].isLock=true;
				}
				if(this.field[f].create==false&&this.columns[f]){//
					this.showColumn(false,f,this.field[f]);
				}
			}
		}
		
		this.resetPageBar(data);
	},
	createRow:function(row,index){
		var _dl=$(document.createElement('dl'));
		_dl.addClass(this.rowCls);
		_dl[0].id=row[this.modelId];
		if(this.autoOddCls&&index%2==1){
			_dl.addClass('x-grid-row-odd');
		}
		
		if(this.hasRowNumber){
			_dl.append(this.createRowNum(this.cellTagName,index));
		}
		if(this.hasCheckBox){
			_dl.append(this.createRowChk(this.cellTagName,row[this.modelId]));
		}
		//自定义行渲染
		if(this.rowRenderer){
			this.rowRenderer.call(this,row,index,_dl);
		}

		for (var c in this.field) {
			
			var _h = this.field[c];
			
			var _dd = document.createElement(this.cellTagName);
			
			var _i=(row[c]==null||row[c]=='null')?'':row[c];
			if(_h.renderer){
				_dd.innerHTML=_h.renderer(_i,c,row);
			}else{
				_dd.innerHTML=_i;			
			}
			_dd.title=_i;
			
			_dd.style.textAlign='center';
			
			
			if(_h.style){
				_s=_h.style.split(';');
				for(var i=0;i<_s.length;i++){
					$(_dd).css(_s[i].split(':')[0],_s[i].split(':')[1]);
				}
			}
			
			if(this.cellBorder){
				_dd.style.borderRightWidth='1px';
				_dd.style.width = _h.width + 'px';
			}else{			
				_dd.style.width = (_h.width+1) + 'px';
			}
			if (_h.create == false) {
				_dd.style.display = 'none';
			}
			_dl.append(_dd);
		}
		return _dl;		
	}, 
	initComponent:function(){
		this.field={};
		Chenxin.UI.JsonGrid.superclass.initComponent.call(this);
	}
});

Chenxin.UI.MultiRowGrid=Chenxin.extend(Chenxin.UI.JsonGrid,{
	cellHeight:16,
	cellBorder:true,
	getCellIndex:function(c,isLock){
		isLock=isLock==undefined?false:isLock;	
		var dom=isLock?this.lockHeadDom:this.headDom;
		var index=-1;
		var _this=this;
		dom.find(this.rowTagName).children().each(function(i){
			if(_this.field[c].p){//组合框
				if(this.f==_this.field[c].p){
					index=i;
					return false;
				}
			}else{//普通框
				if(this.f==c){
					index=i;
					return false;
				}
			}
		});
		return index;
	},	
	showRowColumn:function(index,fn,c){
		this.setFieldAttr(c,'create',fn=='show'?true:false,function(c,f){
			var _this=this;
			this.headExtend.find('li').eq(this.columnIndex[f]).children().eq(0)[fn=='hide'?'removeClass':'addClass']('x-chk-on');
		});
		var _width=this.getColumnsWidth(false);		
		_width=_width<this.bodyDom.width()?this.bodyDom.width():_width;
		
		this.headDom.children().eq(0).width(_width);
		this.bodyDom.children().each(function(){
			$(this).children().eq(index)[fn]();
			$(this).width(_width);
		});
	},
	lockRowCell:function(sourceHeadDom,targetHeadDom,sourceWidth,targetWidth,_index,isLock,c){		
		var sourceBodyDom=isLock?this.bodyDom:this.lockBodyDom;
		var targetBodyDom=isLock?this.lockBodyDom:this.bodyDom;
		
		var sourceRowList=sourceBodyDom.find(this.rowTagName);
		var targetRowList=targetBodyDom.find(this.rowTagName);	

		this.setFieldAttr(c,'isLock',isLock,function(c,f){			
			this.headExtend.find('li').eq(this.columnIndex[f]).children().eq(2)[isLock?'show':'hide']();
		});
		
		//移动Head
		targetHeadDom.find(this.rowTagName).append(sourceHeadDom.find(this.rowTagName).children().eq(_index));
		
		sourceWidth=this.getColumnsWidth(!isLock);
		targetWidth=this.getColumnsWidth(isLock);
		
		
		var _this=this;
		var lockWidth=isLock?targetWidth:sourceWidth;
		
		targetHeadDom.find(this.rowTagName).width(targetWidth);		
		sourceHeadDom.find(this.rowTagName).width(sourceWidth);
		
		//设置两个Dom的宽度
		this.lockDom.width(lockWidth);
		this.unLockDom.width(this.mainDom.width()-lockWidth-1);
		
		
		
		sourceRowList.each(function(i){
			var _tr=targetRowList.eq(i);	
			
			_tr.append($(this).children().eq(_index));
			_tr.width(targetWidth);
			$(this).width(sourceWidth);			
		});
	},
	setFieldAttr:function(c,attr,value,callback){	
		if(this.field[c].p){//组合框			
			for(var f in this.field){
				if(this.field[f].p==this.field[c].p){
					this.field[f][attr]=value;
					if(callback){
						callback.call(this,c,f);
					}
				}
			}
		}
	},
	getColumnsWidth:function(isLock){	
		var _w=0;
		if(isLock||(isLock==false&&!this.lockDom)){
			if(this.hasRowNumber){
				_w+=21;
			}
			if(this.hasCheckBox){
				_w+=21;
			}		
		}
		var field=this.field;
		var p='';
		for(var c in field){
			if(field[c].create!=false){				
				if(isLock==undefined){//锁定状态的
					if(!field[c].p){
						_w+=field[c].width+1;
					}else{
						if(p!=field[c].p){
							p=field[c].p;
							_w+=this.columns[field[c].p].width+1;
						}
					}				
				}else{	
					if(field[c].isLock==undefined){
						field[c].isLock=false;
					}
					if(field[c].isLock==isLock){					
						if(!field[c].p){
							_w+=field[c].width+1;
						}else{
							if(p!=field[c].p){
								p=field[c].p;
								_w+=this.columns[field[c].p].width+1;
							}
						}
					}
				}
			}
		}/* 
		
		var field=this.columns;
		for(var c in field){
			if(field[c].create!=false){
				if(isLock==undefined){
					if(field[c].items){						
						for(var cc in field[c].items){							
							if(field[c].items[cc].create!=false){
								_w+=field[c].width+1;
							}
							break;
						}
					}else{
						_w+=field[c].width+1;					
					}				
				}else{
					if(field[c].isLock==undefined){
						field[c].isLock=false;
					}
					if(field[c].items){
						for(var cc in field[c].items){
							if(field[c].items[cc].isLock==isLock&&field[c].items[cc].create!=false){
								_w+=field[c].width+1;
							}
							break;
						}
					}else{
						if(field[c].isLock==isLock){						
							_w+=field[c].width+1;	
						}
					}
					
				}
			}
		} */
		if(this.gridType!='table'&&isLock==undefined){
			return _w+6;
		}
		return _w;	
	},
	createHeadCell:function(_h,c,dom,level){
		if(!_h.items){
			this.field[c]=_h;
			return this.createHeadCellDom(_h,c,true);
		}else{
			var x=this.createHeadCellDom(_h,c,false,false);
			x.find('span').remove();
			var _level=0;
			for(var _hi in _h.items){
				this.field[_hi]=_h.items[_hi];
				this.field[_hi].p=c;
				var cell=this.createHeadCellDom(_h.items[_hi],_hi,true);
				cell.height(this.cellHeight);
				cell.css('line-height',this.cellHeight+'px');
				x.append(cell);
				if(_level){
					cell.css('border-top-width','1px');
				}
				_level++;
			}
			if(_level>this.maxLevel){
				this.maxLevel=_level;
			}
			return x;	
		}
	},
	createRowChk:function(tagName,id){
		id=id||Math.random()*10000000000;
		var _d=$(document.createElement(this.cellTagName));
		_d.css('border-right-width','1px');
		_d.addClass('x-grid-row-chk');
		var _i=document.createElement('input');
		_i.id='chk_'+id;
		_i.value=id;
		_i.name='chk_row';
		_i.type="checkbox";
		_d.append(_i);
		
		return _d;
		//return '<'+tagName+' class="x-grid-row-chk" style="border-right-width:1px;"><input type="checkbox" id="chk_' + id + '" value="' + id + '" name="chk_row"/></'+tagName+'>';
	},
	createRowNum:function(tagName,index) {
		var _d=$(document.createElement(this.cellTagName));
		
		_d.css('border-right-width','1px');
		_d.addClass('x-grid-row-num');
		_d.text(index);
		return _d;
		//return '<'+tagName+' class="x-grid-row-num" style="border-right-width:1px;">' + (index+1)+ '</'+tagName+'>';
    },
	createRow:function(row,index){
		var _dl=$(document.createElement('dl'));
		_dl.addClass(this.rowCls);
		_dl[0].id=row[this.modelId];
		
		if(index%2==1){
			_dl.addClass('x-grid-row-odd');
		}
		var height=this.maxLevel*this.cellHeight;
		
		_dl.height(height+this.maxLevel-1);
		
		if(this.hasRowNumber){
			var rowCell=this.createRowNum(this.cellTagName,index);
			rowCell.css('height',height+'px');
			rowCell.css('line-height',height+'px');			
			
			_dl.append(rowCell);
		}
		if(this.hasCheckBox){
			var chkCell=this.createRowChk(this.cellTagName,row[this.modelId]);
			
			chkCell.css('height',height+'px');
			chkCell.css('line-height',height+'px');			
			_dl.append(chkCell);
		}
		
		for (var c in this.columns) {
			var _h = this.columns[c];			
			var _dd;
			if(_h.items){
				_dd=$(document.createElement(this.cellTagName));
				var _count=0;
				for(var _hh in _h.items){
					var _hd=this.createRowCell(_h.items[_hh],_hh,row);
					if(_count){
						_hd.css('border-top-width','1px');
					}
					_count++;
					_dd.append(_hd);
				}
			}else{
				_dd=this.createRowCell(_h,c,row);
			}
			if(this.cellBorder){
				_dd.css('border-right-width','1px');
				_dd.width(_h.width);
			}else{		
				_dd.width(_h.width+1);	
			}
			_dd.height(height+this.maxLevel-1);
			_dd.css('line-height',(height+this.maxLevel-1)+'px');
			_dl.append(_dd);
		}
		return _dl;
	},
	createRowCell:function(_h,c,row){
		var _td=document.createElement(this.cellTagName);
		var _i=(row[c]==null||row[c]=='null')?'':row[c];
		if(_h.renderer){
			_td.innerHTML=_h.renderer(_i,_h,row);
		}else{
			_td.innerHTML=_i;			
		}
		_td.title=_i;
		
		_td.style.textAlign='center';
		
		_td.style.width=_h.width+'px';
		_td.style.height=this.cellHeight+'px';
		_td.style.lineHeight=this.cellHeight+'px';
		if(_h.style){
			_s=_h.style.split(';');
			for(var i=0;i<_s.length;i++){
				$(_td).css(_s[i].split(':')[0],_s[i].split(':')[1]);
			}
		}
		if (_h.create == false) {
			_td.style.display = 'none';
		}
		
		return $(_td);
	},
	initComponent:function(){
		Chenxin.UI.MultiRowGrid.superclass.initComponent.call(this);
	}
});

Chenxin.UI.ReportGrid=Chenxin.extend(Chenxin.UI.JsonGrid,{
	hasTotal:true,
	exportAble:true,
	hasPage:false,
	sortStyle:'local',
	totalCls:'x-expand-grid-total',
	render:function(data){	
		Chenxin.UI.ReportGrid.superclass.render.call(this,data);
		if(this.hasTotal&&data.rows.length&&!$('#'+this.renderTo+' .'+this.totalCls).length){
			var total={};
			for(var i=0;i<data.rows.length;i++){
				for(var c in data.rows[i]){
					if(!this.field[c]){
						break;
					}
					if(total[c]==undefined){
						total[c]=0;
					}
					if(typeof(total[c])!='string'){	
						if(this.field[c].inTotal!=false){					
							total[c]+=parseFloat(data.rows[i][c]);
							if(isNaN(total[c])){
								total[c]='合计';
							}
						}else{
							total[c]=' ';
						}
					}
				}
			}
			var totalRow=this.createRow(total,data.rows.length);
			totalRow.addClass(this.totalCls);
			this.bodyDom.append(totalRow);	
			
			this.setBodyRowWidth();		
		}
	},
	initComponent:function(){		
		Chenxin.UI.ReportGrid.superclass.initComponent.call(this);
	}
});

Chenxin.UI.MultiGrid=Chenxin.extend(Chenxin.UI.Grid,{
	hasHead:true,						//是否有头部
	hasFoot:false,						//是否有底部
	expandAble:true,						//是否可以收起
	gridCls:'x-multigrid-main',			//表格样式
	selectCls:'x-multigrid-select',			//行选中样式
	hoverCls:'x-multigrid-hover',			//行滑过样式
	rowCls:'x-multigrid-row',				//行样式
	pageCls:'x-multigrid-page',				//分页工具条样式
	headCls:'x-multigrid-head',				//头部样式
	bodyCls:'x-multigrid-body',				//头部样式
	footCls:'x-multigrid-foot',				//头部样式
	collapseCls:'x-multigrid-collspse',	//收起样式
	expandCls:'x-multigrid-expand',	//展开样式
	sortItems:[{txt:'默认排序',val:''},{txt:'按时间升序',val:'addtime asc',icon:'x-sort-asc'},{txt:'按时间降序',val:'addtime desc',icon:'x-sort-desc'}],	
	btnConfig:[],
	getPageCount:function(count){
		return parseInt(count/this.pageSize)+(count%this.pageSize==0?0:1);
	},
	createHead:function(){
		if(this.hasHead&&!this.headDom){
			var _h=document.createElement('div');
			_h.className=this.headCls;
			var ih='<div class="x-multigrid-rc">共有<span id="'+this.id+'_rc" style="color:#ff0000;">0</span>条记录</div>';
			ih+='<div class="SelectWrapSingle" id="'+this.id+'_sf" style="margin-left:10px; margin-top:4px;"></div>';
			ih+='<dl class="x-multigrid-ps"><dt><input id="'+this.id+'_prev" type="button" name="btn_prev" title="上一页" class="x-multigrid-prev"/></dt><dt><span id="'+this.id+'_rcd">3/30</span></dt><dt><input id="'+this.id+'_next" type="button" name="btn_next" title="下一页" class="x-multigrid-next"/></dt></dl>';
			this.headDom=$(_h);
			this.headDom.append(ih);
			this.el.prepend(_h);
			
			var _this=this;

			this.sortCombo=new Chenxin.UI.Combo({
				containerId:'#'+this.id+'_sf',
				name:'sortField',
				items:this.sortItems,
				addPleaseSelected:false,
				colNum:1,
				colWidth:95,
				onSelected:function(){
					this.sortField=this.getValue();
					_this.reload();
				}
			});
		}		
	},
	createFoot:function(){
		if(this.hasFoot&&!this.footDom){
			var _f=document.createElemnt('div');
			_f.className=this.footCls;
			this.footDom=$(_f);
			this.el.append(_f);
		}
	},
	createBody:function(){
		if(!this.bodyDom){
			var _b=document.createElement('div');
			_b.className=this.bodyCls;
			this.bodyDom=$(_b);
			this.el.append(_b);			
		}	
	},
	init:function(){
		this.createBody();
		if(this.hasFoot){
			this.createFoot();
		}
		
		if(this.height){
			this.el.css('height',this.height+'px');
		}
		if(this.width){
			this.el.css('width',this.width+'px');
		}
		this.el.css('overflow','auto');
		this.el.addClass(this.gridCls);
	},
	reRenderHead:function(count){
		var pageCount=this.getPageCount(count);
		var filter='#'+this.id;
		$(filter+'_rc').html(count);
		$(filter+'_rcd').html((this.pageIndex+1)+'/'+pageCount);
		if(pageCount<=1){
			$(filter+'_prev')[0].className='x-multigrid-prev-disable';
			$(filter+'_next')[0].className='x-multigrid-next-disable';
		}else{
			if(this.pageIndex==0){
				$(filter+'_prev')[0].className='x-multigrid-prev-disable';	
				$(filter+'_next')[0].className='x-multigrid-next';		
			}else if(this.pageIndex==pageCount-1){
				$(filter+'_prev')[0].className='x-multigrid-prev';	
				$(filter+'_next')[0].className='x-multigrid-next-disable';			
			}else{
				$(filter+'_prev')[0].className='x-multigrid-prev';	
				$(filter+'_next')[0].className='x-multigrid-next';				
			}
		}
	},
	render:function(data){	
		if(this.bodyDom){
			this.bodyDom.append(data.html);
		}
		var h=this.bodyDom.find('ul').eq(0).find('li').eq(0).find('dl').length*25;
		this.bodyDom.find('ul').find('li').eq(0).css('height',h+'px');
		var _this=this;
		if(this.expandAble||this.hasCheckBox){
			this.bodyDom.find('ul').each(function(i){
				var _d=document.createElement('div');
				_d.className='x-multigrid-ce';
				
				if(_this.hasCheckBox){
					$(_d).append('<input id="chk_'+_this.id+'_'+this.id+'" name="chk_select" value="'+this.id+'" type="checkbox"/>');
				}
				if(_this.expandAble){
					$(_d).append('<span id="ce_'+this.id+'" title="展开" class="'+_this.collapseCls+'"></span>');
				}
				var _l=$(this).find('li');
				_l.eq(0).prepend(_d);
				_l.eq(1).css('margin-left','20px');
				_l.eq(1).css('margin-right','20px');
				//_l.eq(1).append('<div></div>');
			});
		}
		this.reRenderHead(data.count);
		if(this.hasPage){			
			this.pageBar.reRender(data.count);
		}
	},
	createBtn:function(){
	
	},
	clear:function(){
		this.bodyDom.empty();
	},
	initEvent:function(){		
		var filter='#'+this.id;
		var _this=this;
		$(filter+'_prev').live('click',function(){
			if(this.className=='x-multigrid-prev-disable'){
				return;
			}
			_this.pagIng(-1);
		});
		$(filter+'_next').live('click',function(){
			if(this.className=='x-multigrid-next-disable'){
				return;
			}
			_this.pagIng(1);
		});
		$('.'+this.collapseCls).live('click',function(){
			this.className=_this.expandCls;
			this.title='收起';
			$('#'+this.id.substr(3)).find('li').eq(1).slideDown();
		})
		$('.'+this.expandCls).live('click',function(){
			this.className=_this.collapseCls;
			this.title='展开';
			$('#'+this.id.substr(3)).find('li').eq(1).slideUp();
		});
		
		$('.'+this.rowCls).live('dblclick',function(){
			var _ce=$('#ce_'+this.id);
			if(_ce.hasClass(_this.collapseCls)){			
				$('#'+this.id).find('li').eq(1).slideDown();
				_ce[0].className=_this.expandCls;
				_ce[0].title='收起';
			}else{			
				$('#'+this.id).find('li').eq(1).slideUp();
				_ce[0].className=_this.collapseCls;
				_ce[0].title='展开';				
			}
			
			// this.className=_this.expandCls;
			// this.title='收起';
			// $('#'+this.id.substr(3)).find('li').eq(1).slideDown();
		});
		$('.'+this.rowCls).live('mouseover',function(){
			$(this).toggleClass(_this.hoverCls);
		});
		$('.'+this.rowCls).live('mouseout',function(){
			$(this).toggleClass(_this.hoverCls);
		})
	},
	pagIng:function(v){
		if(this.hasPage){
			this.pageBar.pageIndex+=v;
			this.pageBar.paging();
		}else{			
			this.pageIndex+=v;
			this.reload();
		}
	},
	initComponent:function(){
		delete this.hasRowNum;
		delete this.createRowNum;
		delete this.headSelect;
		Chenxin.UI.MultiGrid.superclass.initComponent.call(this);
	}
});

Chenxin.UI.LockGrid=Chenxin.extend(Chenxin.UI.Grid,{
	initComponent:function(){
		Cehnxin.UI.LockGrid.superclass.initComponent.call(this);
	}
});

Chenxin.UI.ContentGrid=Chenxin.extend(Chenxin.UI.JsonGrid,{
	extensible:false,
	contentField:'',
	autoOddCls:false,
	rowCls:'x-content-grid-row',
    selectCls:'x-content-grid-select', 	//行选中样式
	rowHeadCls:'x-content-grid-rowhead',
	rowContentCls:'x-content-grid-rowcontent',
	cellBorder:true,
	checkIsRowSelect:function(){
		return true;
	},
	renderer:function(){
		this.gridWidth=0;
		if(data.head){
			this.createHead(data.head);
		}
		
		this.bodyDom.empty();
		this.store=data;
		this.createStoreMap();
		if(!this.store.isSort&&this.sortDir.field&&this.sortStyle=='local'){
			this.sortRecord();
			return;
		}
		if (data.rows.length){
			if(data.rows){		
				for(var i=0;i<data.rows.length;i++){
					this.bodyDom.append(this.createRow(data.rows[i],i));
				}
			}else{
				Chenxin.UI.JsonGrid.superclass.render.call(this,data);
			}
		}else{
			this.bodyDom.append('<dl class="x-expand-grid-row"><dd style="width: '+this.el.width()+'px; text-align: center; border-right-width: 1px;">'+this.emptyText+'</dd></dl>');		
		}
		
		if(this.afterRender){
			this.afterRender.call(this,data);
		}
				
				
		this.setBodyRowWidth();
		if(this.ml){
			this.headDom.find('dl').css('margin-left',-this.ml+'px');
			this.bodyDom.scrollLeft(this.ml);
		}
		this.resetPageBar(data);
	},	
	createRow:function(row,index){
		var _dl=Chenxin.UI.ContentGrid.superclass.createRow.call(this,row,index);
		
		var _div=$(document.createElement('div'));
		_div.append(_dl);
		_dl.removeClass(this.rowCls);
		_width=0;
		if(this.hasNumber){
			_width+=21;
		}
		if(this.hasCheckBox){
			_width+=21;
		}
		_div.append('<p>'+row[this.contentField]+'</p>');
		_div.addClass(this.rowCls);
		_div[0].id=_dl[0].id;
		_dl[0].id='';
		return _div;
	}, 
	initComponent:function(){		
		Chenxin.UI.ContentGrid.superclass.initComponent.call(this);
	}
});

/**
*@description 树
*/
Chenxin.UI.Tree=Chenxin.extend(null,{
	actionUrl:'',
	renderTo:'',
	autoLoad:true,
	autoMask:true,
	currentNode:undefined,//当前选中节点，如果是多选，则为全部选中节点数组
	hasCheckBox:false,//是否有checkbox
	// isSelected:true,//区别展开
	levelCount:0,//总共多少层，
	txtField:'txt',
	valField:'val',
	title:'',
	store:[],
	height:400,
	width:200,
	showRoot:true,
	animation:true,//是否执行动画
	timelyLoad:false,//是否及时加载，即点击节点，就调用后台
	singleSelect:true,//选择模式,false为多选
	leafSelect:false,//只选择最底层子节点
	autoSelectChidren:true,//多选是，自动选择子节点
	hoverCls:'orgbgcolor',
	selectedCls:'selected_orgbgcolor',
	collapseCls:'x-closed-default',//收起样式
	expandCls:'x-open-default',//展开样式
	leafCls:'x-leaf-default',//叶节点样式
	titleCls:'x-title',
	onSelected:Chenxin.emptyFn,	//选中节点
	beforeExpand:Chenxin.emptyFn,//展开之前
	beforeReload:Chenxin.emptyFn,//重新加载之前
	param:{},
	/**
	*@description 检查是否添加Checkbox
	*@node 需要检查的节点
	*/
	checkAddChk:function(node){
		if(!node){
			return false;
		}
		if(this.hasCheckBox){//有Checkbox
			if(this.leafSelect){//只有叶节点能选择
				if(node.leaf){
					return true;
				}
				return false;
			}
			return true;
		}
		return false;
	},
	checkIsLeaf:function(items){
		if(!this.levelCount){
			return;
		}
		if(items.length){
			if(items[0].level==this.levelCount){
				this.setLeaf(items);
			}
		}
	},
	setLeaf:function(items){
		if(!items){
			return;
		}
		for(var i=0;i<items.length;i++){
			items[i].leaf=true;
		}
	},
	mask:function(){
		Chenxin.Msg.create({
			id:this.renderTo,
			dom:this.renderTo,
			opcity:10,
			icon:Chenxin.Msg.icon.cycle,
			content:'Loading...'
		});
	},
	unMask:function(){
		Chenxin.Msg.hide(this.renderTo);
	},
	load:function(fatherid){
		fatherid=fatherid||this.root[this.valField];
		fatherid=fatherid.replace(this.prex,'');		
			
		var father=this.findNodeById(fatherid);	
		
		if(father.leaf){
			return;
		}
		if(this.autoMask){
			this.mask();	
		}
		var data={op:'gettree',fatherid:fatherid};
		Chenxin.applyIf(data,this.param);
		Chenxin.ajax({
			url:this.actionUrl,
			data:data,			
			type: "get",
			dataType: "json",
			scope:this,
			onSuccess:function(data,msg){			
				if(!data.items.length){
					father.nochild=true;
					this.unMask();
					return;
				}
				for(var i=0;i<data.items.length;i++){
					if(!data.items[i].children){
						data.items[i].children=[];	
					}
					data.items[i].expand=false;
					data.items[i].fatherId=fatherid;
					data.items[i].level=father.level+1;
					//data.items[i].parentNode=father;
					this.store.push(data.items[i]);
				}
				father.children=data.items;
				
				if(this.checkIsLeaf){//叶节点前端判断
					this.checkIsLeaf.call(this,data.items);
				}
				
				this.render(data.items,father);
				
				if(this.autoMask){
					this.unMask();
				}
			}
		});
	},
	findParentNode:function(node){
		return this.findNodeById(node.fatherId);
	},
	findNodeById:function(id){
		id=id.replace(this.prex,'');
		for(var i=0;i<this.store.length;i++){
			if(this.store[i][this.valField]==id){
				return this.store[i];
			}
		}
		return null;
	},
	resetAllChk:function(domId){
		domId=domId||this.renderTo;
		$('#'+domId+' input:checked').each(function(){
			this.checked=false;
		});
	},
	initStore:function(){
		this.store=[];
		if(!this.root){
			this.root={};
			var rootId=(Math.random()*100000)+'';
			this.root[this.valField]=rootId.split('.')[0];
			this.root[this.txtField]='根节点';
		}
		if(!this.root.children){
			this.root.children=[];
		}
		this.root.expand=false;
		this.root.level=0;
		this.store.push(this.root);
	},
	init:function(){	
		this.bodyDom=$(document.createElement('div'));	
		if(this.height){
			this.dom.css('height',this.height+'px');
			this.bodyDom.css('height',this.height+'px');
		}
		
		if(this.width){
			this.dom.css('width',this.width+'px');	
			this.bodyDom.css('width',this.width+'px');	
		}
		this.dom.css('overflow','hidden');
		this.bodyDom.css('overflow','auto');
		
		//添加title
		if(this.title){
			this.dom.before('<div class="'+this.titleCls+'"><span class="'+this.titleCls+'-l" style="float:left"></span><span class="'+this.titleCls+'-m" style="float:left"><h2>'+this.title+'</h2></span><span class="'+this.titleCls+'-r " style="float:right"></span></div>');		
		}
		
		var cls=this.collapseCls;
		if(this.autoLoad){
			cls=this.expandCls;
			this.root.expand=true;
		}
		var addChk=this.checkAddChk(this.root);
		var _html='<ul>';		
		_html+='<li id="'+this.prex+this.root[this.valField]+'" '+(this.showRoot?'':'style="display:none;"')+'>';
		_html+='<span class="'+(!this.root.leaf?this.collapseCls:this.leafCls)+' x-tree-icon" id="ico_'+this.prex+this.root[this.valField]+'">&nbsp;</span>';//icon
		_html+=(addChk?'<input name="tree-check" type="checkbox" id="chk_'+this.prex+this.root[this.valField]+'"/>':'');//checkbox
		_html+='<span>'+this.root[this.txtField]+'</span>';//内容
		_html+='</li>';
		_html+='<ul>';
		this.bodyDom.append(_html);
		this.dom.append(this.bodyDom);
		this.dom.toggleClass('x-tree');
	},
	onClick:function(el){	
		var x=this.findNodeById(el.id);
		if(this.singleSelect){//单选
			if((this.leafSelect&&x.leaf)||!this.leafSelect){//只能选择叶节点
				if(x.select){
					$(el).removeClass(this.selectedCls);
					this.currentNode=undefined;
					x.select=false;//取出该节点已经被选中标记
				}else{
					$('#'+this.renderTo+' .'+this.selectedCls).removeClass(this.selectedCls);
					$(el).addClass(this.selectedCls);
					if(this.currentNode){
						this.currentNode.select=false;					
					}
					this.currentNode=x;
					x.select=true;//标记该节点已经被选中
				}
				if(this.hasCheckBox){
					this.resetAllChk();
					$('#chk_'+el.id).attr('checked',x.select);
				}
			}
		}else{//多选		
			var _c=$('#chk_'+el.id);
			if((this.leafSelect&&x.leaf)||!this.leafSelect){//只能选择叶节点
				if(x.select){//已经勾选上了，说明已经是选中的，则进行移除
					_c.attr('checked',false);
					$(el).removeClass(this.selectedCls);
					this.currentNode.remove(x);
					x.select=false;
				}else{
					$(el).addClass(this.selectedCls);
					this.currentNode.push(x);
					x.select=true;
				}
				$('#chk_'+el.id).attr('checked',x.select);
				
				if(this.autoSelectChidren&&x.children&&x.children.length){//是否自动选择孩子节点
					this.childrenSelect(x,x.select);
				}
			}
		}
		if(this.onSelected){
			this.onSelected.call(this,x,el);
		}
	},
	/**
	*@description 操作孩子节点选中
	*@node 需要操作的节点
	*@select 是需要选中，还是需要删除
	*/
	childrenSelect:function(node,select){
		for(var i=0;i<node.children.length;i++){
			if(select){//选中
				if(!node.children[i].select){				
					this.currentNode.push(node.children[i]);
					$('#'+this.prex+node.children[i][this.valField]).addClass(this.selectedCls);
					
				}
			}else{//删除			
				this.currentNode.remove(node.children[i]);
				$('#'+this.prex+node.children[i][this.valField]).removeClass(this.selectedCls);
			}
			node.children[i].select=select;
			$('#chk_'+this.prex+node.children[i][this.valField]).attr('checked',select);
			if(node.children[i].children&&node.children[i].children.length){
				this.childrenSelect(node.children[i],select);
			}
		}
	},
	expandNode:function(node){
		if(!node.nochild){	//有孩子节点	
			var _id=this.prex+node[this.valField];
			if(this.beforeExpand){
				this.beforeExpand.call(this,node);
			}
			if($('#_'+_id).length){//已经存在					
				if(this.timelyLoad){//是否及时
					this.load(_id);							
				}else{
					if(this.animation){
						$('#_'+_id).slideDown("fast");
					}else{
						$('#_'+_id).show();
					}
				}
			}else{
				this.load(_id);
			}
		}
		node.expand=true;
	},
	collapseNode:function(node){
		if(!node.nochild){//有孩子节点
			var _id=this.prex+node[this.valField];
			if(this.animation){
				$('#_'+_id).slideUp('fast');
			}else{
				$('#_'+_id).hide();
			}
		}
	
		node.expand=false;
	},
	initEvent:function(){
		var _this=this;
		var filter='#'+this.renderTo+' li';
		$(filter).live('click',function(e){
			if($(e.target).hasClass('x-tree-icon')){//点击图标，不触发onClick事件
				return;
			}
			
			_this.onClick(this);
		});
		
		$(filter+' .x-tree-icon').live('click',function(){
			if(!$(this).hasClass('x-tree-icon')){//非展开按钮，直接返回
				return;
			}
			
			var x=_this.findNodeById(this.id.substr(4));
			
			if(x.leaf){
				return;
			}
			
			if(x.expand){
				_this.collapseNode(x);				
				$(this).removeClass(_this.expandCls);
				$(this).addClass(_this.collapseCls);
			}else{
				_this.expandNode(x);
				$(this).removeClass(_this.collapseCls);
				$(this).addClass(_this.expandCls);
			}
			
			_this.resetSize();
		});
		
		$(filter).live('mouseover',function(){			
			$(this).toggleClass(_this.hoverCls);
		});
		$(filter).live('mouseout',function(){
			$(this).toggleClass(_this.hoverCls);
		});
		this.bodyDom.scroll(function(){
			if(_this.scrollBodyDom){
				_this.scrollBodyDom.call(_this,this);
			}
		});
	},
	scrollBodyDom:Chenxin.emptyFn,
	render:function(items,fatherNode){
		var nodeList='';
		
		$('#_'+this.prex+fatherNode[this.valField]).remove();
		if(items.length){
			var addChk=this.checkAddChk(items[0]);
			var _indent=items[0].level*15;
			if(!this.showRoot){
				_indent-=15;
			}
			for(var i=0;i<items.length;i++){
				nodeList+='<li id="'+this.prex+items[i][this.valField]+'" style="text-indent:'+_indent+'px">';
				nodeList+='<span class="'+(!items[i].leaf?this.collapseCls:this.leafCls)+' x-tree-icon" id="ico_'+this.prex+items[i][this.valField]+'">&nbsp;</span>';//icon
				nodeList+=(addChk?'<input name="tree-check" type="checkbox" id="chk_'+this.prex+items[i][this.valField]+'"/>':'');//checkbox
				nodeList += '<span title=' + items[i][this.txtField] + ((items[i].type == '700') ? ('(' + items[i].code + ')') : '') + '>' + items[i][this.txtField] + ((items[i].type == '700') ? ('(' + items[i].code + ')') : '') + '</span>'; //内容
				nodeList+='</li>';		
			}
			nodeList='<ul id="_'+this.prex+fatherNode[this.valField]+'" '+(this.animation?'style="display:none;"':'')+'>'+nodeList+'</ul>';
			$('#'+this.prex+items[0].fatherId).after(nodeList);
			
			if(this.animation){
				$('#_'+this.prex+items[0].fatherId).slideDown("fast");
			}			
		}
		if(this.afterRender){
			this.afterRender(items);
		}
	},
	resetSize:function(){		
		var w=document.getElementById(this.renderTo).clientWidth;
		$('#'+this.perx+this.renderTo+' ul').each(function(i){
			$(this).css('width',w+'px');
		});
	},
	reload:function(node){
		if(!node){
			node=this.root;
		}
		if(!node[this.valField]){
			return;
		}
		this.removeChildrenNode(node);
		//alert($('#_'+this.prex+node[this.valField]).length);
		$('#_'+this.prex+node[this.valField]).remove();
		if(this.beforeReload){
			this.beforeReload.call(this,node);
		}
		this.load(node[this.valField]);
	},
	removeChildrenNode:function(node){
		if(!node){
			return;
		}
		for(var i=0;i<node.children.length;i++){
			this.removeChildrenNode(node.children[i]);
			this.store.remove(node.children[i]);
		}
	},
	createPrex:function(){
		var _p='cx_'+(Math.random()*1000000);
		_p+='_';
		_p=_p.replace('.','');
		return _p;
	},
	initComponent:function(){
		if(!this.renderTo){
			throw new Error('renderTo is need!');
		}
		this.dom=$('#'+this.renderTo);
		this.prex=this.createPrex();
		
		
		if(!this.singleSelect){//多选
			this.hasCheckBox=true;//多选默认有Checkbox
			this.currentNode=[];
		}
		
		this.initStore();
		this.init();
		
		if(this.autoLoad){
			this.load();
		}
		this.initEvent();
		
	}
});

/**
*@description 树Grid
*/
Chenxin.UI.TreeGrid=Chenxin.extend(Chenxin.UI.Tree,{
	collapseCls:'x-closed-folder',//收起样式
	expandCls:'x-open-folder',//展开样式
	leafCls:'x-leaf-folder',//叶节点样式
	render:function(items){
		var nodeList='';
		if(items.length){
			var addChk=this.checkAddChk(items[0]);
			var _indent=items[0].level*15;
			if(!this.showRoot){
				_indent-=15;
			}
			for(var i=0;i<items.length;i++){
				nodeList+='<li id="'+this.prex+items[i][this.valField]+'" style="text-indent:'+_indent+'px">';
				
				for(var j=0;j<this.column.length;j++){
					var _dd='<dd style="width:'+this.column[j].width+'px;';
					if(j==0){
						_dd+='text-indent:'+_indent+'px;">';
						_dd+='<span class="'+(!items[i].leaf?this.collapseCls:this.leafCls)+' x-tree-icon" id="ico_'+this.prex+items[i][this.valField]+'">&nbsp;</span>';//icon
						_dd+=(addChk?'<input name="tree-check" type="checkbox" id="chk_'+this.prex+items[i][this.valField]+'"/>':'');//checkbox
					}else{
						_dd+='text-indent:0px;text-align:center;">';					
					}
					_dd+='<span>'+(items[i][this.column[j].name]||'')+'</span>';
					_dd+='</dd>';
					
					nodeList+=_dd;
				}
				nodeList+='<dd style="clear:both; display:none"></dd>'				
				
				nodeList+='</li>';	
			}
			nodeList='<ul id="_'+this.prex+items[0].fatherId+'" '+(this.animation?'style="display:none;"':'')+'>'+nodeList+'</ul>';
			$('#'+this.prex+items[0].fatherId).after(nodeList);
			
			if(this.animation){
				$('#_'+this.prex+items[0].fatherId).slideDown("fast");
			}			
		}
		if(this.afterRender){
			this.afterRender(items);
		}
		this.initWidth();
	},
	createHead:function(column){
		column=column||this.column;
		if(column.length){
			var _ul=document.createElement('ul');
			_ul.className='x-tree-header';

			for(var i=0;i<column.length;i++){
				var _li=document.createElement('li');
				if(!column[i].create){
					_li.style.display='none';
				}
				_li.innerHTML=column[i].header;
				_li.style.width=(column[i].width||100)+'px';
				_li.style.height='25px';
				$(_ul).append(_li);
			}
			
			this.headDom=$(document.createElement('div'));
			this.headDom.append(_ul);
			this.dom.prepend(this.headDom);
			this.dom.css('border-top-width','0px');
		}
	},
	initWidth:function(){
		var _width=this.dom.width();
		
		var _w=0;
		for(var i=0;i<this.column.length;i++){
			if(this.column[i].create){
				_w+=(this.column[i].width||100);
			}
		}
		
		if(_width<_w){
			this.dom.css('width',_width+'px');
			this.bodyDom.css('height',(this.dom.height()-25)+'px');
			$('#'+this.renderTo+' ul').each(function(){
				$(this).css('width',(_w+30)+'px');
			});
			this.headDom.find('ul').css('width',(_w+50)+'px');
		}else{			
			this.bodyDom.css('height',(this.dom.height()-28)+'px');
		}
	},
	scrollBodyDom:function(el){
		this.headDom.css('margin-left',-el.scrollLeft+'px');
	},
	initComponent:function(){
		Chenxin.UI.TreeGrid.superclass.initComponent.call(this);
		this.createHead();
	}
});

/**
*@description 树形选择窗体
*/
Chenxin.UI.TreeCombo=Chenxin.extend(Chenxin.UI.Tree,{
	textBoxId:'',
	autoMask:false,
	width:250,
	height:200,
	hasCheckBox:true,
	isShow:false,
	_oldNode:undefined,
	inModelType:'val',//val,txt,all
	txtModelName:'',//TxtModelName
	name:'',
	showRoot:false,
	collapseCls:'x-closed-folder',//收起样式
	expandCls:'x-open-folder',//展开样式
	leafCls:'x-leaf-folder',//叶节点样式
	intervalAutoHide:null,
	value:'',
	text:'',
	required:false,
	initValidator: function() {
		if(!$('#'+this.textBoxId+'Tip').length){
			$('#'+this.textBoxId).after('<div id="' + this.textBoxId + 'Tip" style="float:left; margin-left: 5px; width: 50px; height: 26px; line-height: 26px; text-align: left; display:none" class="onError fl">请选择！</div>');		
		}
    },
    validator: function() {
		if(this.value){
			return true;
		}
        if (!this.required) {
			$('#' + this.textBoxId + 'Tip').hide();
            return true;
        }
		this.initValidator();
		if(this.singleSelect){//单选
			if(!this.currentNode){
				$('#' + this.textBoxId + 'Tip').show();
				return false;			
			}else{
				$('#' + this.textBoxId + 'Tip').hide();
				return true;
			}
		}else{//多选		
			if(!this.currentNode.length){
				$('#' + this.textBoxId + 'Tip').show();
				return false;			
			}else{
				$('#' + this.textBoxId + 'Tip').hide();
				return true;
			}
		}
        return true;
    },
	createSearch:Chenxin.emptyFn,
	getCurrentVal:function(cnList){
		return this.getCurrentV(this.valField,cnList);	
	},
	getCurrentTxt:function(cnList){
		return this.getCurrentV(this.txtField,cnList);
	},
	getCurrentV:function(field,cnList){		
		var _v='';
		cnList=cnList||this.currentNode;
		if(this.singleSelect){
			_v=cnList[field];
		}else{
			for(var i=0;i<cnList.length;i++){
				_v+=cnList[i][field]+',';
			}
			if(_v){
				_v=_v.substr(0,_v.length-1);
			}
		}
		return _v;			
	},
	afterRender:function(items){
		if(!this.value){
			return;
		}
		if(this.leafSelect){//页节点可选，只判断叶节点
			if(items.length&&items[0].leaf){//是叶节点并且有节点
				this.setCheckByValue(items);
			}
		}else{
			this.setCheckByValue(items);	
		}
	},
	setCheckByValue:function(items,value){
		value=value||this.value;		
		items=items||this.store;
		var filter='';
		if(items.length){//有节点
			if(this.singleSelect){//单选
				for(var i=0;i<items.length;i++){
					if(items[i][this.valField]==value){
						filter='#chk_'+this.prex+value;
						items[i].select=true;
						this.currentNode=items[i];
						break;
					}
				}
			}else{//多选
				var _v=','+value+',';
				var _idList=[];
				for(var i=0;i<items.length;i++){
					if(_v.indexOf(','+items[i][this.valField]+',')!=-1){	
						_idList.push('#chk_'+this.prex+items[i][this.valField]);
						items[i].select=true;
						this.currentNode=this.currentNode||[];
						this.currentNode.push(items[i]);
					}
				}
				filter=_idList.join(',');
			}
		}
		
		if(filter){
			$(filter).attr('checked','checked');
		}
	},
	getValue:function(){
		if(this.currentNode){//选过节点
			return this.getCurrentVal();
		}
		return this.value;
	},
	getText:function(){
		if(this.currentNode){//选过节点
			return this.getCurrentTxt();
		}
		return this.text;		
	},	
	setValue:function(val){
		this.value=val;
		this.setText();
	},
	setDefValue:function(){
		this.value='';
		this.text='';
		this.el.val('');
	},
	setText:function(){
		var _this=this;
		var _data={op:'gettext',val:this.value};
		Chenxin.apply(_data,this.param);
		Chenxin.ajax({
			url:this.actionUrl,
			data:_data,
			type:'get',
			onSuccess:function(data,msg){
				_this.text=data.txt;
				_this.el.val(data.txt);
			}
		});
	},
	initCombo:function(){
		this.el.attr('readonly','readonly');
		
		//创建Table
		var _t=document.createElement('table');
		_t.className='x-tree-combo-tab';
		_t.id='tab-'+this.renderTo;
		_t.style.display='none';
		_t.style.width=this.width+'px';
		
				
		if(this.createSearch){
			var _sp=this.createSearch();
			_sp='<span style="padding-left:5px;">查询条件：</span>'+_sp;
			$(_t).append($(document.createElement('tr')).append($(document.createElement('td')).attr('id','sp_'+this.renderTo).append(_sp)));
		}
		$(_t).append($(document.createElement('tr')).append(document.createElement('td')));
		$(_t).append($(document.createElement('tr')).append($(document.createElement('td')).css('text-align','center')));
		$(document.body).append($(_t));
		
		//创建确定按钮
		var _s=document.createElement('input');
		_s.type='button';
		_s.value='确定';
		_s.id='bbar-sure-'+this.renderTo;
		_s.title='确定';
		_s.style.marginRight='10px';
		_s.className='x-tree-combo-btn';
		this.bbarSure=$(_s);
		$('#tab-'+this.renderTo+' td:last').append($(_s));
		
		//创建取消按钮
		var _c=document.createElement('input');
		_c.type='button';
		_c.value='取消';
		_c.id='bbar-cancle-'+this.renderTo;
		_c.title='取消';
		_c.style.marginLeft='10px';
		_c.style.marginRight='10px';
		_c.className='x-tree-combo-btn';
		this.bbarCancle=$(_c);
		$('#tab-'+this.renderTo+' td:last').append($(_c));
		
		
		//创建重置按钮
		var _r=document.createElement('input');
		_r.type='button';
		_r.value='重置';
		_r.id='bbar-reset-'+this.renderTo;
		_r.title='重置';
		_r.style.marginLeft='10px';
		_r.className='x-tree-combo-btn';
		this.bbarReset=$(_r);
		$('#tab-'+this.renderTo+' td:last').append($(_r));
		
		//创建树容器
		var _d=document.createElement('div');
		_d.id=this.renderTo;
		_d.style.width=this.width+'px';
		_d.style.height=this.height+'px';
		_d.className='x-tree-combo';
		if(this.createSearch){		
			$('#tab-'+this.renderTo+' td:eq(1)').append($(_d));
		}else{		
			$('#tab-'+this.renderTo+' td:first').append($(_d));
		}
		
		
		var intervalHide=null;
		var _this=this;	
		
		$(_t).bind('mouseleave',function(){	
			if(_this.isShow){			
				intervalHide=setTimeout(function(){
					_this.setChkByOldNode();
					_this.show(false);
				},200);
			}
		});
		
		$(_t).bind('mouseenter',function(){	
			if(_this.intervalAutoHide){
				clearTimeout(_this.intervalAutoHide);
			}
			if(intervalHide!=null){
				clearTimeout(intervalHide);
			}
		});
	},
	beforeExpand:function(node){
		if(this.createSearch){
			var _p=Chenxin.Fn.getFormJson('sp_'+this.renderTo);
			Chenxin.apply(this.param,_p);
		}
	},
	initEvent:function(){
		var _this=this;		
		$('#bbar-sure-'+this.renderTo).live('click',function(){
			_this.sure();
		});
		$('#bbar-cancle-'+this.renderTo).live('click',function(){
			_this.cancle();
		});
		$('#bbar-reset-'+this.renderTo).live('click',function(){
			_this.reset();
		});
		
		this.el.click(function(){
			if(_this.singleSelect){//单选
				_this._oldNode=_this.currentNode;
			}else{
				if(!_this.oldNode){
				
				}
				_this._oldNode=[];
				for(var i=0;i<_this.currentNode.length;i++){
					_this._oldNode.push(_this.currentNode[i]);
				}
			}
			_this.show(true);
		});
		
		// this.el.blur(function(){
			// _this.intervalAutoHide=setTimeout(function(){
				// _this.setChkByOldNode();
				// _this.show(false);
			// },200);
		// });
		Chenxin.UI.TreeCombo.superclass.initEvent.call(this);
	},
	show:function(isShow){
		if(isShow==undefined){	
			isShow=!this.isShow;
		}
				
		var _tab=$('#tab-'+this.renderTo);
		if(isShow){		
			var offset=this.el.offset();
			_tab.css('left',offset.left+'px');
			
			
			if(_tab.height()+offset.top+this.el.innerHeight()>document.body.clientHeight){
				_tab.css('top',offset.top-_tab.height());
			}else{
				_tab.css('top',offset.top+this.el.innerHeight()+'px');
			}
			
			//_tab.css('top',offset.top+this.el.innerHeight()+'px');
			
			// _tab.slideDown('fast');
			_tab.show();
			// var _this=this;
			// this.intervalAutoHide=setTimeout(function(){
				// _this.setChkByOldNode();
				// _this.show(false);
			// },1000);
		}else{			
			// _tab.slideUp('fast');
				_tab.hide();
		}
		this.isShow=isShow;	
	},
	sure:function(){
		if(this.currentNode){
			this.el.val(this.getCurrentTxt());
		}else{
			this.el.val('');
		}
		
		this.show(false);
	},
	cancle:function(){
		this.setChkByOldNode();
		this.show(false);
	},
	reset:function(){
		
		this.value=undefined;
		
		this.el.val('');
		this.resetAllChk();
		if(this.singleSelect){
			this.currentNode=undefined;
		}else{
			this.currentNode=[];
		}
		this.show(false);
	},
	setChkByOldNode:function(){
		if(this.currentNode!=this._oldNode){
			this.currentNode=this._oldNode;		
			this.resetAllChk();
						
			if(this.singleSelect){				
				if(this._oldNode){
					$('#chk_'+this.prex+this._oldNode[this.valField]).attr('checked','checked');				
				}else if(this.value){
					$('#chk_'+this.prex+this.value).attr('checked','checked');					
				}
			}else{
				for(var i=0;i<this.currentNode.length;i++){
					$('#chk_'+this.prex+this.currentNode[i][this.valField]).attr('checked','checked');					
				}
				if(!this.currentNode&&this.value){
					$('#chk_'+this.prex+this.value.replace(',',',#chk_')).attr('checked','checked');					
				}
			}
		}
	},
	initComponent:function(){
		this.el=$('#'+this.textBoxId);
		this.renderTo='tree-'+this.textBoxId;
		this.title='';
		this.initCombo();
		if(!this.singleSelect){
			this._oldNode=[];
		}
		if(!this.name){
			this.name=this.textBoxId;
		}
		
		Chenxin.UI.TreeCombo.superclass.initComponent.call(this);
		if (this.required) {
            this.initValidator();
        }
	}
        
});
 
/**
*@description 组织结构树形选择下拉框
*/
Chenxin.UI.OrganizationTreeCombo=Chenxin.extend(Chenxin.UI.TreeCombo,{	
	actionUrl:'/service/OrganizationTreeCombo.ashx',
	leafSelect:true,
	param:{type:0},
	root:{
		val:'00000000-0000-0000-0000-000000000000',
		txt:'易居臣信',
		type:'0'
	},
	beforeExpand:function(node){
		this.param.type=node.type;
		Chenxin.UI.OrganizationTreeCombo.superclass.beforeExpand.call(this,node);
	},
	initComponent:function(){
		Chenxin.UI.OrganizationTreeCombo.superclass.initComponent.call(this);
	}
});

/**
*@description 部门树形下拉选择框
*/
Chenxin.UI.DepartTreeCombo=Chenxin.extend(Chenxin.UI.OrganizationTreeCombo,{	
	checkIsLeaf:function(items){
		if(items.length){
			if(items[0].type=='500'||items[0].type=='600'){
				for(var i=0;i<items.length;i++){
					items[i].leaf=true;
				}
			}
		}				
	},
	setText:function(){
		this.param.txttype='user';
		Chenxin.UI.DepartTreeCombo.superclass.setText.call(this);
	},
	initComponent:function(){
		Chenxin.UI.DepartTreeCombo.superclass.initComponent.call(this);	
	}
});

/**
*@description 人员树形下拉选择框
*/
Chenxin.UI.UserTreeCombo=Chenxin.extend(Chenxin.UI.OrganizationTreeCombo,{	
	hasSearch:true,//是否有查询条件
	checkIsLeaf:function(items){
		if(items.length){
			if(items[0].type=='700'){
				for(var i=0;i<items.length;i++){
					items[i].leaf=true;
				}
			}
		}				
	},
	createSearch:function(){
		return '<input type="radio" name="status" value="1" id="r_'+this.prex+this.renderTo+'_at" checked="checked"/><label for="r_'+this.prex+this.renderTo+'_at">在职</label>'+'<input type="radio" name="status" value="0" id="r_'+this.prex+this.renderTo+'_lv"/><label for="r_'+this.prex+this.renderTo+'_lv">离职</label>'
	},	
	setText:function(){
		this.param.txttype='user';
		Chenxin.UI.UserTreeCombo.superclass.setText.call(this);
	},
	initEvent:function(){
		var _this=this;
		$('#sp_'+this.renderTo+' input[name="status"]').live('click',function(){
			_this.param.status=this.value;
			_this.param.type=0;
			_this.reload();
		});
		Chenxin.UI.UserTreeCombo.superclass.initEvent.call(this);
	},
	initComponent:function(){
		this.param.status=1;
		if(!this.hasSearch){
			this.createSearch=undefined;
		}
		Chenxin.UI.UserTreeCombo.superclass.initComponent.call(this);	
	}
});

/**
*@description 有简单，快捷选择模式的属性选择框
*/
Chenxin.UI.RichModelTreeCombo=Chenxin.extend(Chenxin.UI.UserTreeCombo,{
	activeIndex:0,//当前有快速,0为快速选择，1为详细选择
	valueIndex:1,//当前是否是快速选择选中,0为快速选择，1为详细选择
	validator:function(){
	
		if(!this.valueIndex){					
			if (!this.required) {
				$('#' + this.textBoxId + 'Tip').hide();
				return true;
			}
			this.initValidator();
			if(this.singleSelect){//单选
				if(!this.qcNode){
					$('#' + this.textBoxId + 'Tip').show();
					return false;			
				}else{
					$('#' + this.textBoxId + 'Tip').hide();
					return true;
				}
			}else{//多选		
				if(!this.qcNode.length){
					$('#' + this.textBoxId + 'Tip').show();
					return false;			
				}else{
					$('#' + this.textBoxId + 'Tip').hide();
					return true;
				}
			}
			return true;
		}else{
			return Chenxin.UI.RichModelTreeCombo.superclass.validator.call(this);
		}
	},
	createModel:function(){
		var _ul=document.createElement('ul');
		_ul.className='x-tree-tabs';
		_ul.style.width=this.width+'px';
		_ul.id='tabsmenu_'+this.renderTo;
		var _qli=document.createElement('li');
		_qli.innerHTML='快速模式';
		_qli.className='x-tree-tab-active';
		$(_ul).append(_qli);
		var _dli=document.createElement('li');
		_dli.innerHTML='详细模式';
		_dli.className='x-tree-tab-numal';
		$(_ul).append(_dli);
		
		var _this=this;
		$(_qli).click(function(){
			$('#'+_this.renderTo).hide();
			$('#qmodel_'+_this.renderTo).show();
			_qli.className='x-tree-tab-active';
			_dli.className='x-tree-tab-numal';
			_this.activeIndex=0;
		});
		
		$(_dli).click(function(){
			$('#'+_this.renderTo).show();
			$('#qmodel_'+_this.renderTo).hide();
			_dli.className='x-tree-tab-active';
			_qli.className='x-tree-tab-numal';
			_this.activeIndex=1;
		});
		
		$('#'+this.renderTo).before(_ul);
	},
	createQuickDiv:function(){
		this.dom.before('<div id="qmodel_'+this.renderTo+'" class="x-tree-qmodel"></div>');
		this.dom.hide();
	},
	loadUser:function(fatherid,type){
		if(!fatherid){
			return;
		}
		this.fatherid=fatherid;
		var data={op:'getdepartuser',fatherid:fatherid};
		var _p=Chenxin.Fn.getFormJson('sp_'+this.renderTo);
		Chenxin.apply(this.param,_p);
		Chenxin.apply(data,this.param);
		Chenxin.ajax({
			url:this.actionUrl,
			data:data,			
			type: "get",
			dataType: "json",
			scope:this,
			onSuccess:function(data,msg){
				this.qStore=data.items;
				this.renderUser(data.items);				
			}
		});
	},
	clearUserItems:function(){
		$('#qmodel_'+this.renderTo+' ul').text('');
	},
	renderUser:function(items){
		var _ul=$('#qmodel_'+this.renderTo+' ul');
		if(!_ul.length){
			_ul=$(document.createElement('ul'));
			$('#qmodel_'+this.renderTo).append(_ul);
		}else{
			_ul.text('');
		}
		
		for(var i=0;i<items.length;i++){
			_ul.append('<li id="qli_'+items[i][this.valField]+'"><span class="x-leaf-folder-icon"></span><input id="qchk_'+this.prex+items[i][this.valField]+'" value="'+items[i][this.valField]+'" name="chk_val" type="checkbox"/><span>'+items[i][this.txtField]+'('+items[i].code+')'+'</span></li>');
		}
	},
	sure:function(){
		if(this.qStore.length){//有快速
			if(this.activeIndex==0){//当前为快速，且有选中
				if(this.qcNode){
					this.el.val(this.getCurrentTxt(this.qcNode));				
				}else{
					this.el.val('');
				}
				this.show(false);
				this.valueIndex=0;
			}else{
				this.valueIndex=1;
				Chenxin.UI.RichModelTreeCombo.superclass.sure.call(this);
			}
		}else{
			this.valueIndex=1;
			Chenxin.UI.RichModelTreeCombo.superclass.sure.call(this);
		}
	},
	getValue:function(){
		if(!this.valueIndex){
			if(this.qcNode){
				return this.getCurrentVal(this.qcNode);				
			}else{
				return '';
			}
		}else{
			return Chenxin.UI.RichModelTreeCombo.superclass.getValue.call(this);
		}
	},
	getText:function(){
		if(!this.valueIndex){
			if(this.qcNode){
				return this.getCurrentTxt(this.qcNode);				
			}else{
				return '';
			}
		}else{
			return Chenxin.UI.RichModelTreeCombo.superclass.getText.call(this);
		}		
	},
	reset:function(){
		if(this.qcNode){
			this.qcNode=this.singleSelect?undefined:[];
			$('#qmodel_'+this.renderTo).find('input').removeAttr('checked');
		}
		Chenxin.UI.RichModelTreeCombo.superclass.reset.call(this);
	},
	show:function(){
		Chenxin.UI.RichModelTreeCombo.superclass.show.apply(this,arguments);
		if(this.isShow){
			var _a=$('#tabsmenu_'+this.renderTo+' li');
			if(!this.qStore.length){//快速搜索没有
				if(this.activeIndex==1){
					return;
				}
				$('#qmodel_'+this.renderTo).hide();
				this.dom.show();
				$(_a[0]).removeClass('x-tree-tab-active');
				$(_a[0]).addClass('x-tree-tab-numal');
				
				$(_a[1]).removeClass('x-tree-tab-numal');
				$(_a[1]).addClass('x-tree-tab-active');
				this.activeIndex=1;
			}else{
				if(this.activeIndex==0){
					return;
				}
				$('#qmodel_'+this.renderTo).show();
				$('#'+this.renderTo).hide();
				$(_a[1]).removeClass('x-tree-tab-active');
				$(_a[1]).addClass('x-tree-tab-numal');
				
				$(_a[0]).removeClass('x-tree-tab-numal');
				$(_a[0]).addClass('x-tree-tab-active');	
				this.activeIndex=0;		
			}
		}
	},
	findQNode:function(id){
		id=id.replace('qli_','');
		for(var i=0;i<this.qStore.length;i++){
			if(this.qStore[i][this.valField]==id){
				return this.qStore[i];
			}
		}
		return null;
	},
	initEvent:function(){
		var _this=this;
		$('#qmodel_'+this.renderTo+' li').live('mouseover',function(){
			$(this).toggleClass(_this.hoverCls);
		});
		$('#qmodel_'+this.renderTo+' li').live('mouseout',function(){
			$(this).toggleClass(_this.hoverCls);
		});
		
		$('#qmodel_'+this.renderTo+' li').live('click',function(){
			if(_this.singleSelect){
				_this.resetAllChk('#qmodel_'+_this.renderTo);
			}
			var _chk=$('#qchk_'+_this.prex+this.id.replace('qli_',''));
			if(_this.singleSelect){
				_chk.attr('checked','checked');
			}
			if(_chk.attr('checked')){//选中
				if(_this.singleSelect){//单选
					_this.qcNode=_this.findQNode(this.id);
				}else{
					_this.qcNode.push(_this.findQNode(this.id));
				}				
			}else{
				if(_this.singleSelect){//单选
					_this.qcNode=null;
				}else{//多选移除
					var _index=-1;
					for(var i=0;i<_this.qcNode.length;i++){
						if(_this.qcNode[i][_this.valField]==this.id.replace('qli_','')){
							_index=i;
							break;
						}
					}
					if(_index!=-1){
						_this.qcNode.splice(_index,1);
					}
				}								
			}
			$(this).addClass(_this.hoverCls);
		});
		
		
		$('#sp_'+this.renderTo+' input[name="status"]').live('click',function(){
			_this.loadUser(_this.fatherid);
		});
		
		Chenxin.UI.RichModelTreeCombo.superclass.initEvent.call(this);
	},
	initComponent:function(){
		this.qStore=[];
		Chenxin.UI.RichModelTreeCombo.superclass.initComponent.call(this);		
		this.createModel();
		this.createQuickDiv();
		if(!this.singleSelect){
			this.qcNode=[];
		}
	}
});

Chenxin.UI.WinCombo=Chenxin.extend(null,{
	actionUrl:'',
	inModelName:{},
	autoLoad:true,
	comboType:'wincombo',
	inModelType:'val',
	id:'',
	containerId:'',
	type:'numalcombo',
	displayDom:{},
	emptyText:'请选择',
	idField:'val',							//数据中不同于其项的列名
	tips:'',								//注意事项
	tipsCls:'x-wincombo-tips',				//样式
	cls:'x-wincombo',
	clsR:'x-wincombo-r',
	clsT:'x-wincombo-t',
	sdCls:'x-wincombo-select-dom',			//选中项Dom样式
	siCls:'x-wincombo-select-item',			//选中项样式
	oiCls:'x-wincombo-option-item',			//选项Dom样式
	odCls:'x-wincombo-option-dom',			//选项样式
	oiHoverCls:'x-wincombo-option-hover',	//选项划过样式
	barCls:'x-wincombo-bar-dom',			//工具条Dom样式
	sodCls:'x-wincombo-expand-dom',			//点击展开下一级Dom的样式
	loadingCls:'x-wincombo-loading',							//加载中样式
	tbxWidth:170,
	width:0,
	baseParam:{},
	sBaseParam:{},
	param:{},
	sItems:{},
	tsItems:{},
	items:{},
	flCanSelected:false,					//第一层可以选中
	sTipsF:'',								//第一层选中提示
	sTipsS:'',								//第二层选中提示
	fSelectedLimit:0,						//第一层选中数控制
	sSelectedLimit:0,						//第二层选中数控制
	onSelected:Chenxin.emptyFn,
	cSyncP:true,							//展开子节点同步父节点
	cSyncPType:'same',						//子节点同步父几点类型，same为子节点选中时父节点选中，diff相反
	cSyncPTips:'不能选中此项',						//违反同步的操作提示
	/**
	*@description用于扩展更多事件
	*@param 
	*/
	onClick:function(level,itemIndex,el,spanIndex){//选项点击
		if(level=='level_2'||(level=='level_1'&&this.flCanSelected&&spanIndex==0)){//第二层或第一层的选中框且第一层可选中
			this.selected(level,itemIndex,el);
			return;
		}
		this.showExpand(level,itemIndex,el);
	},
	showExpand:function(level,itemIndex,el){
		var _l='level_'+(parseInt(level.replace('level_',''))+1);
	
		var _exp=$('#expand_'+this.id+'_'+(_l)+'_'+itemIndex);
		$('.'+this.sodCls).hide();
		
		if(!_exp.length){
			var _d=document.createElement('ul');
			_d.id='expand_'+this.id+'_'+(_l)+'_'+itemIndex;
			_d.className=this.sodCls;
			_d.innerHTML='<div class="'+this.loadingCls+'"></div>';
			_d.style.top=$(el).offset().top+20+'px';
			_d.style.left=$(el).offset().left+'px';
			
			//$(document.body).append(_d);
			this.sodom.append(_d);
			
			var _hide=null;
			var _autoHide=null;
			_autoHide=setTimeout(function(){
				$(_d).hide();
			},2000);
			
			$(_d).bind('mouseout',function(){
				_hide=setTimeout(function(){
					$(_d).hide();
				},200);
			});
						
			$(_d).bind('mouseover',function(){
				if(_autoHide){
					clearTimeout(_autoHide);
				}
				if(_hide){
					clearTimeout(_hide);
				}
			});
			Chenxin.apply(this.param,this.sBaseParam);
			//this.param.key='System.Block';
			this.param.subkey=this.items[level][itemIndex].val;
			this.param.recordid=this.items[level][itemIndex].id;
			this.load($(_d),_l,el);			
		}else{
			_exp.css('top',$(el).offset().top+20+'px');
			_exp.css('left',$(el).offset().left+'px');
			_exp.show();
		}
	},
	selected:function(level,itemIndex,el,selected){		
		if(!this.tsItems[level]){
			this.tsItems[level]=[];
		}
		
		if(selected==undefined){
			selected=this.items[level][itemIndex].selected;
		}
		
		if(!selected&&this.cSyncP){//选中
			var _level='level_'+(parseInt(level.replace('level_',''))+1);
			if(this.tsItems[_level]){
				for(var i=0;i<this.tsItems[_level].length;i++){
					var _index=this.tsItems[_level][i];
					if(this.items[_level][_index].dom.find('li').eq(0)[0].p.i==itemIndex){
						alert(this.cSyncPTips);
						return;
					}
				}			
			}
		}
		
		if(selected){
			$(el).find('span').eq(0).removeClass('x-wincom-chk-on');
			this.items[level][itemIndex].selected=false;
			this.tsItems[level].remove(itemIndex);
		}else{
			$(el).find('span').eq(0).addClass('x-wincom-chk-on');	
			this.items[level][itemIndex].selected=true;
			this.tsItems[level].remove(itemIndex);
			this.tsItems[level].push(itemIndex);
		}
		
		
		if(el.p&&this.cSyncP&&!selected){//有父节点,且同步，且子节点都是选中操作
			if(this.cSyncPType=='same'){//同步
				this.selected(el.p.l,el.p.i,el.p,false);
			}else if(this.cSyncPType=='diff'){//异步
				this.selected(el.p.l,el.p.i,el.p,true);
			}else{//互不干涉
			
			}
		}
		
		
		this.renderSelected(level);
		
		// if(this.onSelected){
			// this.onSelected.call(this,this.items[index]);		
		// }	
	},
	renderSelected:function(level,sItems){
		var dom=level=='level_1'?this.fsdom.find('dd'):this.sdom.find('dd');
		dom.empty();
		
		if(!this.tsItems[level].length){
			$(dom).text('您还没有选中任何项');
			return;
		}
		
		var _this=this;
		
		sItems=sItems||this.tsItems;
		
		for(var i=0;i<sItems[level].length;i++){
			var _index=sItems[level][i];
			var _jli=this.createItemsEl({
				item:this.items[level][_index],
				itemIndex:_index,
				level:level,
				isSelected:true,
				onClick:this.clearSelected,
				scope:this				
			});//this.createItemsEl(this.items[level][_index],_index,level,true,this.clearSelected,this);
			dom.append(_jli);			
		}
	},
	clearSelected:function(level,itemIndex,li){		
		//delete this.tsItems[level][index];
		this.tsItems[level].remove(itemIndex);
		this.items[level][itemIndex].selected=false;
		$(li).remove();
		var item=this.items[level][itemIndex]
		
		item.dom.find('li').eq(item.li).find('span').eq(0).removeClass('x-wincom-chk-on');
	},
	
	getValue:function(){
		var _value='';
		for(var level in this.sItems){
			_value+=this.getValueByLevel(level);
		}
		return _value;
	},
	getValueByLevel:function(level){
		return this.getFieldValue(level,'val');	
	},
	getText:function(){
		var _text='';
		for(var level in this.sItems){
			_text+=this.getTextByLevel(level);
		}
		return _text;
	},
	getTextByLevel:function(level){
		return this.getFieldValue(level,'txt');
	},
	getFieldValue:function(level,field){
		var _t='';
		if(this.sItems[level]){
			for(var i=0;i<this.sItems[level].length;i++){
				_t+=this.items[level][this.sItems[level][i]][field]+',';
			}
		}
		return _t;
	},
	setValue:function(){
		this.clear();
	},
	sure:function(){
		this.win.hide();
		this.sItems=new Object();
		
		for(var level in this.tsItems){
			this.sItems[level]=new Array();
			for(var i=0;i<this.tsItems[level].length;i++){
				this.sItems[level].push(this.tsItems[level][i]);
			}
		}
		
		this.reSetDisplay();
	},
	cancle:function(){
		this.win.hide();
			
		this.resetSelected();	
		this.reSetDisplay();
	},
	validator:function(){
		return true;
	},
	clear:function(){
		//this.win.hide();
		this.sItems=new Object();
		this.resetSelected();
		this.tsItems=new Object();
		this.reSetDisplay();
	},
	reSetDisplay:function(){
		if(this.type=='numalcombo'){		
			var _s=this.el.find('span').eq(0);
			
			_s.text(this.getText()||this.emptyText||'请选择');
			_s.attr('title',_s.text());
		}else{
			for(var l in this.displayDom){
				this.displayDom[l].text(this.getTextByLevel(l)||this.emptyText||'请选择');
			}
		}
	},
	resetSelected:function(){
		for(var level in this.tsItems){
			for(var i=0;i<this.tsItems[level].length;i++){
				var _index=this.tsItems[level][i];
				
				this.items[level][_index].selected=false;
				this.items[level][_index].dom.find('li').eq(this.items[level][_index].li).find('span').eq(0).removeClass('x-wincom-chk-on');
			}
			
			var dom=level=='level_1'?this.fsdom.find('dd'):this.sdom.find('dd');
			dom.html('您还没有选中任何项');

			
			if(this.sItems[level]){
				for(var i=0;i<this.sItems[level].length;i++){
					var _index=this.sItems[level][i];
					
					this.items[level][_index].selected=true;
					this.items[level][_index].dom.find('li').eq(this.items[level][_index].li).find('span').eq(0).addClass('x-wincom-chk-on');
				}
				
				this.renderSelected(level,this.sItems);			
			}
			
			
		}
	},
	createSelectDom:function(tips){
		var _d=$(document.createElement('dl'));
		_d.addClass(this.sdCls);
		_w=this.width||this.win.width;
		_d.append('<dt>'+(tips||'已选中项')+'：</dt><dd style="width:'+(_w-134)+'px">您还没有选中任何项</dd>')
		return _d;
	},
	createOptionDom:function(){		
		var _d=document.createElement('div');
		_d.className=this.odCls;
		
		return $(_d);
	},
	createBarDom:function(){
		var _d=document.createElement('dl');
		_d.className=this.barCls;
		
		return $(_d);	
	},
	createTipsDom:function(){
		return '<div class="'+this.tipsCls+'">'+this.tips+'</div>';
	},
	createBottomBar:function(dom){	
		dom=dom||this.bdom;
		var _this=this;
		var _li=document.createElement('li');
		_li.className=this.oiCls;
		_li.title='全选/反选';
		
		$(_li).append('<span class="x-wincom-chk-off"></span>');
		$(_li).append('<span>全选/反选</span>');
		
		$(_li).bind('mouseover',function(){
			$(this).addClass(_this.oiHoverCls);
		});
		$(_li).bind('mouseout',function(){
			$(this).removeClass(_this.oiHoverCls);
		});
				
		$(_li).bind('click',function(e){
			var _liList=dom.find('li');
			for(var i=0;i<_liList.length;i++){
				var _l=_liList.eq(i)[0];
				if(_l.l){
					_this.selected.call(_this,_l.l,_l.i,_li);				
				}
			}
		});	
		var barDom=this.createBarDom();
		barDom.append(_li);
		dom.append(barDom);
	},
	createWin:function(){
		var _this=this;
		return new Chenxin.UI.Win({
			id:'win_'+this.id,
			height:300,		
			afterClose:function(){
				_this.cancle();
			},
			title:'请选择区域/板块',
			createBtn:function(){
				return [{
					text:'清空',
					handler:_this.clear,
					scope:_this
				},{
					text:'确定',
					handler:_this.sure,
					scope:_this
				},{
					text:'取消',
					handler:_this.cancle,
					scope:_this
				}]
			}
		});
	},
	createItemsEl:function(config){	
		var _li=document.createElement('li');
		_li.className=this.oiCls;
		_li.title=config.item.txt;
		
		_li.v=config.item.val;
		_li.i=config.itemIndex;
		_li.l=config.level;
		
		if(config.parentEl){
			_li.p=config.parentEl;
		}
		
		var _jli=$(_li);
		//item.dom=_jli;
		
		_jli.append('<span class="x-wincom-chk-off'+(config.isSelected?' x-wincom-chk-on':'')+'"></span>');
		_jli.append('<span>'+config.item.txt+'</span>');
		
		_jli.bind('mouseover',function(e){
			if($(this).hasClass(config.scope.oiHoverCls)){
				return;
			}
			$(this).addClass(config.scope.oiHoverCls);
		});
		_jli.bind('mouseleave',function(e){
			$(this).removeClass(config.scope.oiHoverCls);
		});
		
		$(_li).find('span').each(function(_in){	
			$(this).bind('click',{level:config.level,itemIndex:config.itemIndex,li:_li,onClick:config.onClick,scope:config.scope},function(e){			
				e.data.onClick.call(e.data.scope,e.data.level,e.data.itemIndex,e.data.li,_in);
			});	
		});
		
		return _jli;
	},
	render:function(data,dom,level,pel){
		var _this=this;
		dom=dom||this.odom;
		dom.empty();
		var _length=level=='level_1'?0:this.items[level].length;
		for(var i=0;i<data.items.length;i++){
		
			data.items[i].li=i;	
			data.items[i].dom=dom;
			
			var _jli=this.createItemsEl({
				item:data.items[i],
				parentEl:pel,
				itemIndex:_length+i,
				level:level,
				isSelected:false,
				onClick:this.onClick,
				scope:this			
			});
			
			if(level!='level_1'){
				this.items[level].push(data.items[i]);
			}
			dom.append(_jli);
		}
		
		//this.createBottomBar(dom);
	},
	load:function(renderDom,level,pel){
		var _this = this;
		var _d={};
		Chenxin.apply(_d,this.baseParam);
		Chenxin.apply(_d,this.param);
        Chenxin.ajax({
			type: 'get',
			dataType: 'json',
			url: this.actionUrl,
			data: _d,
			scope: this,
			onSuccess: function(data, msg) {
				if (data.items == undefined) {
					data.items = [];
				}
				level=level||'level_1';
				if(!this.items[level]){
					this.items[level]=[];
				}
				if(level=='level_1'){
					this.items[level]=data.items;
				}
				
				renderDom=renderDom||this.odom;
				
				this.render(data,renderDom,level,pel);
				if(this.afterLoad){
					this.afterLoad(data,renderDom,level);
				}			
			}
		});
	},
	reload:function(param){
		if(param){
			this.param=param;		
		}
		this.odom.empty();
		this.sodom.empty();
		this.clear();
		this.load();
	},
	initEvent:function(){
		var _this=this;
		this.el.bind('click',function(){
			_this.win.show();
			_this.tsItems=new Object();
			for(var level in _this.sItems){
				_this.tsItems[level]=new Array();
				for(var i=0;i<_this.sItems[level].length;i++){
					_this.tsItems[level].push(_this.sItems[level][i]);
				}
			}
		});
	},
	init:function(){
		if(this.type=='numalcombo'){		
			this.el.addClass(this.cls);
			this.el.width(this.tbxWidth||115);
			this.el.append('<span class="'+this.clsT+'" style="width:'+(this.tbxWidth-15)+'px">'+(this.emptyText||'请选择')+'</span><span class="'+this.clsR+'"></span>');
		}
		this.win=this.createWin();
		if(this.tips){//创建提示
			this.win.bodyDom.append(this.createTipsDom());
		}
		if(this.flCanSelected){//第一层可以选
			this.fsdom=this.createSelectDom(this.sTipsF);
			this.win.bodyDom.append(this.fsdom);
		}
		this.sdom=this.createSelectDom(this.sTipsS);
		
		this.sodom=this.createOptionDom();
		this.sodom.removeClass(this.odCls);
		$(document.body).append(this.sodom);
		this.odom=this.createOptionDom(this.sTipsS);
		//this.bdom=this.createBarDom();
		//this.createBottomBar();
		this.win.bodyDom.append(this.sdom);
		this.win.bodyDom.append(this.odom);
		this.win.bodyDom.append('<div style="clear:both"></div>')
		this.win.bodyDom.css('position','relative');
		//this.win.bodyDom.append(this.bdom);
	},
	initComponent:function(){
		if(!this.id){
			this.id=this.containerId;
		}
		this.el=$('#'+this.containerId);
		this.init();
		this.initEvent();
		if(this.autoLoad){
			this.load();
		}
	}
});

Chenxin.UI.RegionBlockWinCombo=Chenxin.extend(Chenxin.UI.WinCombo,{
	tips:'选中区域隶属板块之后，该区域将被剔除,且不能被再次选中！',
	inModelName:{Block:'level_2',Region:'level_1'},
	actionUrl:'/service/selector.ashx',
	baseParam:{key:'System.Region',filter:'bycity',type:'datadic'},
	sBaseParam:{key:'System.Block'},
	inModelType:'txt',
	flCanSelected:true,						//父级层次可以选中	
	sTipsF:'已选中区域',								//第一层选中提示
	sTipsS:'已选中板块',								//第二层选中提示
	cSyncPTips:'已选中下属板块，不能选中此区域！',		//违反同步操作提示
	cSyncPType:'diff',
	reload:function(param){
		param=param||{};
		Chenxin.apply(param,{key:'System.Region',filter:'bycity',type:'datadic'});
		Chenxin.UI.RegionBlockWinCombo.superclass.reload.call(this,param);
	},
	getValue:function(modelName){		
		if(modelName){
			return Chenxin.UI.RegionBlockWinCombo.superclass.getValueByLevel.call(this,this.inModelName[modelName]);		
		}else{
			return Chenxin.UI.RegionBlockWinCombo.superclass.getValue.call(this);			
		}
	},
	getText:function(modelName){
		if(modelName){
			return Chenxin.UI.RegionBlockWinCombo.superclass.getTextByLevel.call(this,this.inModelName[modelName]);		
		}else{
			return Chenxin.UI.RegionBlockWinCombo.superclass.getText.call(this);			
		}
	},
	createBlockDom:function(index){
		var _d=$(document.createElement('div'));
		_d.attr('id','div_'+index);
	},
	initComponent:function(){
		Chenxin.UI.RegionBlockWinCombo.superclass.initComponent.call(this);
	}
});

Chenxin.UI.RegionAreaWinCombo=Chenxin.extend(Chenxin.UI.WinCombo,{	
	tips:'选中区域隶属板块之后，该区域将被剔除,且不能被再次选中！',
	inModelName:{Region:'level_1',Area:'level_2'},
	actionUrl:'/service/selector.ashx',
	baseParam:{key:'System.Region',filter:'bycity',type:'datadic'},
	sBaseParam:{key:'System.Area'},
	inModelType:'txt',
	flCanSelected:true,						//父级层次可以选中	
	sTipsF:'已选中区域',								//第一层选中提示
	sTipsS:'已选中片区',								//第二层选中提示
	cSyncPTips:'已选中下属板块，不能选中此区域！',		//违反同步操作提示
	//cSyncPType:'same',
	cSyncP:false,
	value:{Area:'',Region:''},
	text:{Area:'',Region:''},
	reload:function(param){
		param=param||{};
		Chenxin.apply(param,{key:'System.Region',filter:'bycity',type:'datadic'});
		Chenxin.UI.RegionBlockWinCombo.superclass.reload.call(this,param);
	},
	getValue:function(modelName){
		if(modelName){
			var _v=Chenxin.UI.RegionBlockWinCombo.superclass.getValueByLevel.call(this,this.inModelName[modelName]);
			if(!_v){
				_v=this.value[modelName];
			}
			return _v==undefined?'':_v;
			//return Chenxin.UI.RegionBlockWinCombo.superclass.getValueByLevel.call(this,this.inModelName[modelName]);		
		}else{
			return Chenxin.UI.RegionBlockWinCombo.superclass.getValue.call(this);			
		}
	},
	getText:function(modelName){
		if(modelName){
			var _t=Chenxin.UI.RegionBlockWinCombo.superclass.getTextByLevel.call(this,this.inModelName[modelName]);	
			if(!_t){
				_t=this.text[modelName];
			}
			return _t==undefined?'':_t;
			//return Chenxin.UI.RegionBlockWinCombo.superclass.getTextByLevel.call(this,this.inModelName[modelName]);		
		}else{
			return Chenxin.UI.RegionBlockWinCombo.superclass.getText.call(this);			
		}
	},
	createBlockDom:function(index){
		var _d=$(document.createElement('div'));
		_d.attr('id','div_'+index);
	},
	initComponent:function(){
		Chenxin.UI.RegionAreaWinCombo.superclass.initComponent.call(this);
	}
});

/**
*@description 添加页面基类
*/
Chenxin.UI.AddPageCommon=Chenxin.extend(null,{
    actionUrl:'',
    /**
	*@description 初始化页面元素事件处理，需重写
	*/
	initEvent:Chenxin.emptyFn,
    /**
	*@description 用户自定义页面初始化方法
	*/
	customerInit:Chenxin.emptyFn,
	/**
	*@description 创建Form
	*/
	createForm:Chenxin.emptyFn,
    initComponent:function(){

        //创建表单
		if(this.createForm){
			this.form=this.createForm();
		}
		        
        //页面初始化
        if(this.customerInit){
			this.customerInit();
		}
	
        //绑定元素页面事件
		if(this.initEvent){
			this.initEvent();		
		}
    }
});

/**
*@description 添加页面窗体基类
*/
Chenxin.UI.AddFormCommon=Chenxin.extend(null,{
    id:'',
	additionalParam:{},
	autoAlertSucc:true,		//保存成功后是否自动弹出保存成功的消息
	autoReset:true,			//保存成功后是否自动重置表单项
	op:'add',
	uploadFile:false,
	fileNames:[],
	saveNames:[],
	comboList:[],
	formValConfig:{},
	initEvent:Chenxin.emptyFn,
	saveSucc:Chenxin.emptyFn,
	saveFail:Chenxin.emptyFn,
	delSucc:Chenxin.emptyFn,
	delFail:Chenxin.emptyFn,
	initFormValidator:Chenxin.emptyFn,
	createComboList:Chenxin.emptyFn,
	manualReset:Chenxin.emptyFn,
	loadDefVal:Chenxin.emptyFn,
	initForm:Chenxin.emptyFn,
	manualPreCheck:Chenxin.emptyFn,
	delFile:function(fileName){
	    for(var idxCnt = 0; idxCnt < this.fileNames.length; idxCnt++ ){
	        if(fileName == this.fileNames[idxCnt]){
	            this.fileNames.splice(idxCnt,1);
	            this.saveNames.splice(idxCnt,1);
	            break;
	        }
	    }
	},
    getParam:function(){
		var json=Chenxin.Fn.getFormJson(this.id,this.comboList);		
		if(this.afterGetFormJson){
			var scope=this.scope
			if(this.scope==window){
				scope=this;
			}
			this.afterGetFormJson.call(scope,json);
		}
		return json;
	},
	checkCombo:function(){
		var count=0;
		for(var i=0;i<this.comboList.length;i++){
			if(!this.comboList[i].validator()){
				count++;
			}
		}
		if(count){
			return false;
		}
		return true;
	},
    formValidator:function(model){
		if(this.initFormValidator){
			if(!jQuery.formValidator.pageIsValid(this.id)||!this.checkCombo()){
				alert('请填写完必填(选)项再进行表单提交！');
				return false;
			}
		}else{
			if(!this.checkCombo()){
				alert('请填写完必填(选)项再进行表单提交！');
				return false;
			}
		}
		if(this.customerFormVal){
			return this.customerFormVal(model);
		}
		return true;
	},
	resetFormValidator:function(){
	    if (this.initFormValidator) {
            jQuery.formValidator.resetTipState(this.id);	
		}
	},
	reset:function(){
		Chenxin.Fn.setFormValue(this.id,this.comboList,{});
		if( this.manualReset!= undefined){
		    this.manualReset();
		}
	},
	save:function(){
	
	    Chenxin.Msg.Saving.show();
		var model=this.getParam();

		if(!this.formValidator(model)){	
			Chenxin.Msg.Saving.hide();
			return;
		}
		if( this.manualPreCheck != undefined ){
		    if(this.manualPreCheck() == false){
		        Chenxin.Msg.Saving.hide();
		        return;
		    }
		}
		var _data={
			op:this.op
		};
		var m=model.toString();
		if(m!='{}'){			
			_data.model=m;
		}
		if(this.uploadFile == true){
		    if(this.fileNames.length > 0){
		        _data.filenames = this.fileNames.toString();
		        _data.savenames = this.saveNames.toString();
		    }
		}
		Chenxin.apply(_data,this.additionalParam);
		var _this=this;
		Chenxin.ajax({
			type: "post",
			dataType: "json",
			url: this.actionUrl,
			data: _data,
			onSuccess: function(data,msg) {
			    Chenxin.Msg.Saving.hide();
			    if(_this.autoAlertSucc){
					alert(msg);
				}
				if(_this.saveSucc){		
					_this.saveSucc.call(_this.scope,data,msg);
				}
				if(_this.autoReset){
					_this.reset.call(_this);
					_this.resetFormValidator.call(_this);		
				}
			},
			onFail:function(data,msg){
				Chenxin.Msg.Saving.hide();	
				if(_this.saveFail){
					_this.saveFail(_this.scope,data,msg);
				}					
			}
		});
    },
    del:function(){
        if( this.currentId == undefined ){
            alert("没有要删除的信息");
            return;
        }
        if( !confirm("确定要删除吗？")){
            return;
        }
        var _data={
			op:this.op,
			RecordId:this.currentId
		}
        var _this=this;
		Chenxin.ajax({
			type: "post",
			dataType: "json",
			url: this.actionUrl,
			data: _data,
			onSuccess: function(data,msg) {
			    Chenxin.Msg.Saving.hide();
			    if(_this.autoAlertSucc){
					alert(msg);
				}
				if(_this.delSucc){		
					_this.delSucc.call(_this.scope,data,msg);
				}
			},
			onFail:function(data,msg){
				Chenxin.Msg.Saving.hide();	
				if(_this.delFail){
					_this.delFail(_this.scope,data,msg);
				}					
			}
		});
    },
    initComponent:function(){
        
        if(!this.id){
			throw new Error('id is need!');
			return; 
		}
		
		//页面初始化
		if(this.initForm){
		    this.initForm();
		}
		
		if(this.createComboList){
			this.comboList=this.createComboList();
		}
		//初始化窗体验证
		if(this.initFormValidator){		
			Chenxin.apply(this.formValConfig,{
			    onsuccess:function(){return true;},
			    validatorgroup:this.id
            });
			jQuery.formValidator.initConfig(this.formValConfig);
			this.initFormValidator();
		}
		//初始化事件
		if(this.initEvent){
			this.initEvent();
		}
		//页面初始化
		if(this.loadDefVal){
		    this.loadDefVal();
		}
    }
});


Chenxin.UI.Tab=Chenxin.extend(null,{
	id:'',
	mainCls:'x-tab-main',
	tabCls:'x-tab-title',
	headCls:'x-tab-head',
	bodyCls:'x-tab-body',
	activeCls:'x-tab-active',
	numalCls:'x-tab-numal',
	activeIndex:0,
	tabWidth:100,
	height:400,
	afterActive:Chenxin.emptyFn,
	activeTab:function(index){		
		this.tabTList.eq(this.activeIndex).removeClass(this.activeCls);
		this.tabTList.eq(this.activeIndex).addClass(this.numalCls);
		this.tabCList.eq(this.activeIndex).hide();
		this.activeIndex=index;
		this.tabTList.eq(this.activeIndex).removeClass(this.numalCls);
		this.tabTList.eq(this.activeIndex).addClass(this.activeCls);
		this.tabCList.eq(this.activeIndex).show();
		
		if(this.afterActive){
			this.afterActive.call(index);
		}
	},
	init:function(){
		var _this=this;
		this.el.addClass(this.mainCls);
		this.headDom.addClass(this.headCls);
		this.bodyDom.addClass(this.bodyCls);
		
		this.tabCList.hide();
		this.tabTList.each(function(i){
			this.index=i;
			$(this).width(_this.tabWidth);
			$(this).append('<span></span>');
			$(this).addClass(_this.tabCls);
			$(this).addClass(_this.numalCls);
			
			
			$(this).bind('click',function(){
				if(this.index==_this.activeIndex){
					return;
				}
				_this.activeTab(this.index);
			});
			
		});
		this.activeTab(this.activeIndex);
	},
	initComponent:function(){
		this.el=$('#'+this.id);
		this.headDom=$('#'+this.id+'>ul');
		this.bodyDom=$('#'+this.id+'>div');		
		this.tabTList=$('#'+this.id+'>ul>li');
		this.tabCList=$('#'+this.id+'>div>div');
		
		this.init();
	}
});















/**
*@description 重写Object对象的toString方法，用户JSON对象的字符串化
*/
Object.prototype.toString=function(){	
	var str='';
	for(var p in this){
		var val=this[p];
		if(val==null||val==undefined){
			val='';
		}
		str+=p+':"'+val+'",';
	}
	if(str.length){
		str=str.substring(0,str.length-1);
	}
	return '{'+str+'}';
}
/**
*@description 数组删除指定元素
*/
Array.prototype.remove=function(val){
	if(val==undefined){
		return;
	}
	if($.isArray(val)){//数组
		for(var i=0;i<val.length;i++){
			this.remove(val[i]);
		}
	}else{	
		var _index=-1;
		for(var i=0;i<this.length;i++){
			if(this[i]==val){
				_index=i;
				break;
			}
		}
		if(_index!=-1){
			this.splice(_index,1);
		}
	}
}

Array.prototype.add=function(item){
	
	if(item==undefined){
		return;
	}
	if($.isArray(item)){//数组
		for(var i=0;i<item.length;i++){
			this.add(item[i]);
		}
	}else{	
		this.push(item);
	}
}

/**
 * 判断元素的值是否为空
 *
 * 根据结果返回true,false
 */
String.prototype.isBlank = function() {
	 return (this==null || this.trim()=="" || typeof(this)=="undefined");
}

/**
 * 字符串左边补str
 */
 String.prototype.padLeft = function(length,str) {
    var strRet;
    if(this == ""){
        strRet = this;
    }else{
        var cntGap = length - this.length;
        strRet = this;
        if(cntGap > 0){
            for(var idx = 0; idx < cntGap ;idx++ ){
                strRet = str + strRet;
            }
        }
    }
    return strRet;
 }
/**
 * 字符串右边补str
 */
 String.prototype.padRight = function(length,str) {
    var strRet;
    if(this == ""){
        strRet = this;
    }else{
        var cntGap = length - this.length;
        strRet = this;
        if(cntGap > 0){
            for(var idx = 0; idx < cntGap ;idx++ ){
                strRet = strRet + str;
            }
        }
    }
    return strRet;
 }
/**
 * 字符串转换为大写
 */
String.prototype.toUpper = function() {
    return this.toUpperCase();
}

/**
 * 字符串转换为小写
 */
String.prototype.toLower = function() {
    return this.toLowerCase();	
}

/**
 * 去掉字符串两端的空白字符
 */
String.prototype.trim = function() {
    return this.replace(/(^\s+)|(\s+$)/g, "");
}

/** 
 * 去掉字符串左边的空白字符
 */
String.prototype.ltrim = function() {
    return this.replace(/(^\s+)/g, "");	
}

/** 
 * 去掉字符串左边的空白字符
 */
String.prototype.rtrim = function() {
    return this.replace(/(\s+$)/g, "");	
}

/** 
 * 去掉字符串中间的所有空白字符
 */
String.prototype.atrim = function() {
    return this.replace(/(\s)/g, "");	
}

/**
 * 比较字符串
 *
 * 根据结果返回 -1, 0, 1
 */
String.prototype.compareTo = function(str) {
    if (this == str) {
        return 0;
    } else if (this < str) {
        return -1;
    } else {
        return 1;
    }
}

/** 
 *  忽略大小写比较字符串是否相等
 * 
 *  根据结果返回true,false
 */
String.prototype.isEquals = function (str) {
		return this.toLower() == str.toLower();
}

/**
 * 判断字符串是否以指定的字符串开始
 */
String.prototype.startsWith = function(str) {
    return this.substr(0, str.length) == str;
}

/**
 * 判断字符串是否以指定的字符串开始，忽略大小写
 */
String.prototype.iStartsWith = function(str) {
    return this.substr(0, str.length).isEquals(str);
}

/**
 * 判断字符串是否以指定的字符串结束
 */
String.prototype.endsWith = function(str) {
    return this.substr(this.length - str.length) == str;
}

/**
 * 判断字符串是否以指定的字符串结束，忽略大小写
 */
String.prototype.iEndsWith = function(str) {
    return this.substr(this.length - str.length).isEquals(str);
}

/**
 * 判断字符串是否为数字类型
 *
 * 对于省略写法，科学计数法，十六进制。都会认为是数字
 */
String.prototype.isNum = function() {
	  return !isNaN(Number(this));
}

/**
 * 判断字符串是否为半角
 *
 */
String.prototype.isDbccase = function() {

		reg=/[\u0000-\u00ff]/g
		
		return reg.test(this);	
}

/**
 * 判断字符串是否是电话号码，传真号码
 *
 * 电话号码可以+开头，可以含有“-”
*/ 
String.prototype.isTel = function() {
	
	  //国家代码(2到3位)-区号(2到3位)-电话号码(7到8位)-分机号(3位)"
	 	var pattern =/^(([0\+]\d{2,3}-)?(0\d{2,3})-)?(\d{7,8})(-(\d{3,}))?$/;
	 	
	 	return pattern.test(this);
}

/**
 * 判断字符串是否是手机
 *
*/
String.prototype.isMobile = function() {
			var checkFlag=false;

			var reg0 = /^13\d{5,9}$/;   //130--139。至少7位
			var reg1 = /^15\d{5,9}$/;  //联通153。至少7位
			var reg2 = /^18\d{9}$/;  //移动159。至少7位
			var reg3 = /^14\d{5,9}$/;  //联通153。至少7位

			if (reg0.test(this)) checkFlag = true;
			if (reg1.test(this)) checkFlag = true;
			if (reg2.test(this)) checkFlag = true;
			if (reg3.test(this)) checkFlag = true;
			
			return checkFlag;
}

/**
 * 判断字符串是否是邮箱
 */
String.prototype.isMail = function() {	
			//字符串必须包含“@”，“.”
			pattern = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;

			return pattern.test(this);
}

/**
 * 判断字符串是否是邮编
 */
String.prototype.isPost = function() {			
			//邮编必须是6位的数字
			pattern = /^[0-9]{6}$/;
			
			return pattern.test(this);
}

/**
 * 验证日期是否合法
 *
 * 日期格式包括：“yyyyMMdd”，“yyyy-MM-dd”，“yyyy/MM/dd”
 */
String.prototype.isDate = function() {

		var pattern = /^(?:(?!0000)[0-9]{4}[\-\/\s]?(?:(?:0[1-9]|1[0-2])[\-\/\s]?(?:0[1-9]|1[0-9]|2[0-8])|(?:0[13-9]|1[0-2])[\-\/\s]?(?:29|30)|(?:0[13578]|1[02])[\-\/\s]?31)|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)[\-\/\s]?02[\-\/\s]?29)$/;

  	return pattern.test(this);
}

/**
	* 验证身份证
	*
	* 身份证格式：15位纯数字，或者17数字+ 一位数字或者“X”
	*/
String.prototype.isIdCardNo = function() {
    var area = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外" }

    var idcard, Y, JYM;
    var S, M;
    var idcard_array = new Array();
    idcard = this;
    idcard_array = idcard.split("");
    //地区检验
    if (area[parseInt(idcard.substr(0, 2))] == null) return false;
    //身份号码位数及格式检验
    switch (idcard.length) {
        case 15:
            if ((parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0 || ((parseInt(idcard.substr(6, 2)) + 1900) % 100 == 0 && (parseInt(idcard.substr(6, 2)) + 1900) % 4 == 0)) {
                ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$/; //测试出生日期的合法性
            } else {
                ereg = /^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$/; //测试出生日期的合法性
            }
            if (ereg.test(idcard)) return true;
            else return false;
            break;
        case 18:
            //18位身份号码检测
            //出生日期的合法性检查
            //闰年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))
            //平年月日:((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))
            if (parseInt(idcard.substr(6, 4)) % 4 == 0 || (parseInt(idcard.substr(6, 4)) % 100 == 0 && parseInt(idcard.substr(6, 4)) % 4 == 0)) {
                ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$/; //闰年出生日期的合法性正则表达式
            } else {
                ereg = /^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$/; //平年出生日期的合法性正则表达式
            }
            if (ereg.test(idcard)) {//测试出生日期的合法性
                //计算校验位
                S = (parseInt(idcard_array[0]) + parseInt(idcard_array[10])) * 7
                + (parseInt(idcard_array[1]) + parseInt(idcard_array[11])) * 9
                + (parseInt(idcard_array[2]) + parseInt(idcard_array[12])) * 10
                + (parseInt(idcard_array[3]) + parseInt(idcard_array[13])) * 5
                + (parseInt(idcard_array[4]) + parseInt(idcard_array[14])) * 8
                + (parseInt(idcard_array[5]) + parseInt(idcard_array[15])) * 4
                + (parseInt(idcard_array[6]) + parseInt(idcard_array[16])) * 2
                + parseInt(idcard_array[7]) * 1
                + parseInt(idcard_array[8]) * 6
                + parseInt(idcard_array[9]) * 3;
                Y = S % 11;
                M = "F";
                JYM = "10X98765432";
                M = JYM.substr(Y, 1); //判断校验位
                if (M == idcard_array[17]) return true; //检测ID的校验位
                else return false;
            }
            else return false;
            break;
        default:
            return false;
            break;
    }
}


if(jQuery)(
	function(jQuery){
		jQuery.extend(jQuery.fn,{
			defText:function(options){
				jQuery(this).each(function(){
					var settings=jQuery.extend({
						deftxt:'请输入...'
					},options);
					this.value=settings.deftxt;
					
					
					this.defVal=settings.deftxt;
					$(this).bind('click',function(){
						if(this.value==this.defVal){						
							this.value='';
						}
					});
					$(this).bind('blur',function(){
						if(this.value==''){
							this.value=this.defVal;
						}
					});
					
				});
			},
			numberText:function(options){
				
				jQuery(this).each(function(){
					
					var settings=jQuery.extend({
						acceptEnter:true,
						minValue:undefined,
						maxValue:undefined,
						acceptDecimal:true//接受小数点
					},options);
				
					//var _oldValue=0;
					
					$(this).bind('keydown',function(e){
						//_oldValue=parseFloat(this.value);
						if(settings.acceptEnter&&e.keyCode==13){//Enter
							return true;
						}
						if(e.keyCode==8){//BackSpace BackSpace 
							return true;
						}
						if(e.keyCode==9){//Tab 
							return true;
						}
						if(e.keyCode==46){//Delete
							return true;
						}
						if((e.keyCode>46&&e.keyCode<58)||(e.keyCode>95&&e.keyCode<106)){//number
							return true;
						}
						if(settings.acceptDecimal&&(e.keyCode==190||e.keyCode==110)){//Decimal
							return true;
						}
						return false;
					});
					$(this).bind('change',function(e){
						var _newValue=parseFloat(this.value);
						if(settings.minValue!=undefined&&_newValue<settings.minValue){
							if(this.defVal){
								this.value=this.defVal;
							}else{
								this.value='';
							}
						}
						if(settings.maxValue!=undefined&&_newValue>settings.maxValue){
							if(this.defVal){
								this.value=this.defVal;
							}else{
								this.value='';
							}
						}						
					});
				});
			}
		})
})(jQuery);

